如何识别正在单击的数字键盘上的键? [英] How do I recognize key on numpad is being clicked?
问题描述
我使用 bind()
为按键设置操作,但是当我想为数字键盘上的数字键添加操作时,它不起作用.如果我想让它工作,代码应该怎么看?
实际上取决于 NumLock 键的状态.
为了识别按下了哪个键,tkinter event
对象具有三个属性:char
、keysym
和 keycode代码>.
关注键盘数字,NumLock 开启这些是 (0-9):
char keysym 键码'0' '0' 96'1' '1' 97'2' '2' 98'3' '3' 99'4' '4' 100'5' '5' 101'6' '6' 102'7' '7' 103'8' '8' 104'9' '9' 105
当 NumLock 关闭时,这些是 (0-9):
char keysym 键码'' '插入' 45'' '结束' 35'' '下' 40'' '下一个' 34'' '左' 37'' '清除' 12'' '正确' 39'''家' 36'''上' 38'' '之前' 33
现在,对于数字(所以 NumLock ON),char
和 keysym
是相同的,但是 keycode
对于小键盘数字和字母上方的正常行是不同的.例如,数字行中的2有keycode
50
,而小键盘中的2有keycode
98
.
但是,当 NumLock 关闭时,这些键与具有相同含义的其他键无法区分.例如,普通的End和键盘中1下面的都有keycode
35
.>
因此,无论 NumLock 的状态如何,要检查小键盘上的 1 键,您需要检查 keycode
是否为97
或 35
.但是,这确实意味着按常规的 End 键将具有相同的效果,我不知道有什么方法可以阻止这种情况.
我使用以下代码检查上面发布的所有值:
导入 tkinter 作为 tk根 = tk.Tk()定义键(事件):打印(repr(event.char),repr(event.keysym),repr(event.keycode))root.bind("", key)root.mainloop()
I use bind()
to set actions for keys, but when I want to add action to number keys on Numpad it doesn't work. How should the code look if I want it to work?
It actually depends on the state of the NumLock key.
To identify which key has been pressed, the tkinter event
object has three attributes: char
, keysym
and keycode
.
Focussing on the keypad numbers, with NumLock ON these are (0-9):
char keysym keycode
'0' '0' 96
'1' '1' 97
'2' '2' 98
'3' '3' 99
'4' '4' 100
'5' '5' 101
'6' '6' 102
'7' '7' 103
'8' '8' 104
'9' '9' 105
With NumLock OFF these are (0-9):
char keysym keycode
'' 'Insert' 45
'' 'End' 35
'' 'Down' 40
'' 'Next' 34
'' 'Left' 37
'' 'Clear' 12
'' 'Right' 39
'' 'Home' 36
'' 'Up' 38
'' 'Prior' 33
Now, for the numbers (so NumLock ON), the char
and keysym
are the same, but keycode
is different for the numpad numbers and the normal row above the letters. For example, the 2 in the number row has keycode
50
, while the 2 in the numpad has keycode
98
.
However, with NumLock OFF, the keys are indistinguishable from the other keys with the same meaning. For example, both the normal End and the one under the 1 in the keypad have keycode
35
.
So to check for the 1 key on the numpad regardless of the state of NumLock, you need to check for the keycode
being either 97
or 35
. However, this does mean that pressing the regular End key will have the same effect and I don't know of any way to stop this.
I used the following code to check all values posted above:
import tkinter as tk
root = tk.Tk()
def key(event):
print(repr(event.char), repr(event.keysym), repr(event.keycode))
root.bind("<Key>", key)
root.mainloop()
这篇关于如何识别正在单击的数字键盘上的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!