0

我正在使用 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。谢谢!

4

1 回答 1

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()
于 2012-07-23T02:56:14.837 回答