[Raspberry PI 3 b +,Python]首先,我会为我的语言技巧道歉。
我正在为键盘事件编码Tkinter,像(向上)(向下)这样的键盘命令按钮工作正常但普通字符不起作用(例如1-9,A-Z)
我累了
frame.bind('<Left>', leftKey) # THIS OK
frame.bind('<Right>', rightKey) # THIS OK
但
frame.bind('<1>', leftKey) # Not work
frame.bind('1', leftKey) # Not work
frame.bind("1", leftKey) # Not work
我想使用键盘字符按钮与Up,Down按钮一样正常工作。
"1"
和'1'
应该工作。 "<1>"
代表鼠标按钮1。
如果绑定到框架,则必须确保它具有键盘焦点。默认情况下,帧没有键盘焦点。
例如,要强制键盘焦点到框架,您需要调用focus_set
:
frame.focus_set()
如果框架没有焦点,可能会发生这种情况,因此frame.bind('<1>', leftKey)
不起作用。
您可以通过打印frame.focus_get()
来检查哪个小部件具有焦点。
您可以在绑定回调之前将焦点设置到帧
例:
from tkinter import *
root = Tk()
root.geometry('100x100+100+100')
frame = Frame(root)
frame.pack()
frame.focus_set() # This will get the frame in focus.
# If the frame is in focus the bind will work.
frame.bind( "1", lambda _: print(frame.focus_get()) )
root.mainloop()
要么
只需将其绑定到主窗口即可。
from tkinter import *
root = Tk(). # Main window
# bind the callback to the main window.
root.bind( '1', lambda k: print(k) )
root.mainloop()