askdirectory() changes focus to different window
Question: I am using Tkinter to build two windows. One the main one, pressing a button
leads to the creation of the second window.

This second window does not get focus immediately when it created. That I am
able to fix by calling .focus_force(). However, when I call the askdirectory()
function from tkFileDialog, the focus changes back to the first window.

How can I prevent that focus switch from happening, without simply calling
focus_force() all over the place?

To replicate problem:

    
    
    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
    

I am using Python 2.7.3. Thanks!


Answer: the little-documented wm_attributes method might help:

    
    
    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()
    

