开发者

How come the second call to the Python app doesn't have keyboard focus

开发者 https://www.devze.com 2023-02-07 12:41 出处:网络
If I call this class twice, the first time the keyboard focus goes to the window. The second time it doesn\'t. The escape key is used to close the window and it works the first time. The second time t

If I call this class twice, the first time the keyboard focus goes to the window. The second time it doesn't. The escape key is used to close the window and it works the first time. The second time the window must be clicked in with the mouse before the escape key will work. Is there something going on with the focus not being passed back? I've run into this problem a number of times but here I've caught it as simple as possible. Here's the code:

from T开发者_如何学Gokinter import *

class Dialog(): # imagine this having buttons and stuff
    def __init__(self):
        root = Tk()
        root.bind_all('<Escape>', lambda event :root.destroy())
        root.mainloop()

# this simulates running a python terminal app which invokes a dialog at some point
Dialog() # this one accepts the key action
Dialog() # this one needs a mouse click in the window first


I just ran the code, and in Windows 7, it doesn't take focus either time.

What OS are you running it in?

Also, you can force focus to the root window by throwing in this line.

root.focus_force()


On a Mac using X11 as the window server and using either an X terminal or a regular terminal, the focus always goes to the Dialog window so the escape key works both times. On windows XP running from a cmd.exe terminal, the focus only goes to the dialog the first time. The second time you must click the window first. However, using root.focus_force() makes it work everywhere. Thanks a bunch!

0

精彩评论

暂无评论...
验证码 换一张
取 消