Search code examples
pythontkintertabscursor

python tkinter - get cursor in new window


I'd like to use the tab key in both showing of the following code:

from tkinter import *
main = Tk() 
def pressButton():
        main.destroy()
End=Button(main,text='Finished',width=15,command=pressButton).grid()
main.mainloop()

from tkinter import *
main = Tk() 
def pressButton():
        main.destroy()
End=Button(main,text='Finished',width=15,command=pressButton).grid()
main.mainloop()

first window works: i can press tab and space and it opens the second window; there i'm not able to "press button" by using tab and space, because the cursor is in Python Shell. How can I get the cursor in the second window?


Solution

  • As mention in that post "Tkinter main window focus", it is possible to force the focus to the main window.

    Solution - add a call to the after() to focus_force().

    from tkinter import *
    main = Tk() 
    def pressButton():
        main.destroy()
    End=Button(main,text='Finished',width=15,command=pressButton).grid()
    # call the focus_force() after the window is displayed
    main.after(1, lambda: main.focus_force())
    main.mainloop()