簡體   English   中英

Tkinter鍵盤事件不適用於角色

[英]Tkinter keyboard event dosen't work with characters

[Raspberri PI 3 b +,Python]首先,我會道歉我的語言能力。

我正在為鍵盤事件編碼Tkinter,像(向上)(向下)這樣的鍵盤命令按鈕運行良好,但正常的字符不起作用(例如1-9,AZ)

我累了

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按鈕一樣正常工作。

如果框架沒有焦點,可能會發生這種情況,因此frame.bind('<1>', leftKey)將不起作用。

您可以通過print 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()

"1"'1'應該有效。 "<1>"表示鼠標按鈕1。

如果綁定到框架,則必須確保它具有鍵盤焦點。 默認情況下,幀沒有鍵盤焦點。

例如,要強制鍵盤焦點到框架,您需要調用focus_set

frame.focus_set()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM