我正在使用Tkinter构建两个窗口。一个是主按钮,按下按钮可以创建第二个窗口。
第二个窗口在创建时不会立即获得焦点。我可以通过调用.focus_force()来解决这个问题。但是,当我从tkFileDialog调用askdirectory()函数时,焦点会变回第一个窗口。
如何在不调用focus_force()的情况下阻止焦点切换发生?
要复制问题:
from Tkinter import *
from tkFileDialog import *
class app:
def __init__(self, master):
Button(master, command = make_new).grid()
def make_new(self):
root = Tk()
new = new_win(root)
root.mainloop() #here the focus is on the first window
class new_win:
def __init__(self, master):
f = askdirectory() #even after placing focus on second window,
#focus goes back to first window here
我正在使用Python 2.7.3。谢谢!
答案 0 :(得分:0)
文档很少的wm_attributes方法可能有所帮助:
from Tkinter import *
import tkFileDialog
root = Tk()
top = Toplevel()
top.wm_attributes('-topmost', 1)
top.withdraw()
top.protocol('WM_DELETE_WINDOW', top.withdraw)
def do_dialog():
oldFoc = top.focus_get()
print tkFileDialog.askdirectory()
if oldFoc: oldFoc.focus_set()
b0 = Button(top, text='choose dir', command=do_dialog)
b0.pack(padx=100, pady=100)
def popup():
top.deiconify()
b0.focus_set()
b1 = Button(root, text='popup', command=popup)
b1.pack(padx=100, pady=100)
root.mainloop()