How Do I Recognize Key On Numpad Is Being Clicked?
Solution 1:
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()
defkey(event):
print(repr(event.char), repr(event.keysym), repr(event.keycode))
root.bind("<Key>", key)
root.mainloop()
Post a Comment for "How Do I Recognize Key On Numpad Is Being Clicked?"