python tkinter - 获取新的光标 window

python tkinter - get cursor in new window

我想在显示以下代码时都使用 Tab 键:

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

第一个 window 有效:我可以按 Tab 和 space 并打开第二个 window;我无法通过使用制表符和 space 来 "press button",因为光标在 Python Shell 中。 如何在第二个window中获取光标?

如 post "Tkinter main window focus" 中所述,可以将焦点强制到主要 window。

解决方案 - 添加对after()的调用到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()