2012-07-17 77 views
0

我正在使用Tkinter構建兩個窗口。一個主要的,按下按鈕導致創建第二個窗口。askdirectory()將焦點更改爲不同的窗口

第二個窗口創建時不會立即獲得焦點。我可以通過調用.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

的小記錄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()