I'm using Python's Tkinter for a little project, and I need to use the number pad for key binding. However, the keys 1, 2, 3, 4, and 5 are not responding. All other keys work just fine. For example:
from tkinter import *
window = Tk()
window.title('Key Test')
c = Canvas(window, height=500, width=500)
c.pack()
word = c.create_text(250, 250, text='Spam')
def transformation(event):
c.itemconfig(word, text='Spamalot')
c.bind_all('<6>', transformation)
The above code works perfectly fine. But putting '5' in the binding rather than '6' makes the program unresponsive. I have tried doing this in other windows, and I have even tried using a different keyboard.
Nothing seems to work. Can anyone shed some light on this issue?
I have no idea why <6>
works, but the key events are officially called <Key-…>
, see the keysyms manual page:
c.bind_all('<Key-5>', transformation)
EDIT Based on Jason Harper's and Mike - SMT's suggestion, I looked at the Tk source code (in generic/tkBind.c
), and it indeed does this:
if ((*field >= '1') && (*field <= '5') && (field[1] == '\0')) {
if (eventFlags == 0) {
patPtr->eventType = ButtonPress;
eventMask = ButtonPressMask;
} else if (eventFlags & KEY) {
goto getKeysym;
} else if (!(eventFlags & BUTTON)) {
…
}
patPtr->detail.button = (*field - '0');
} else {
getKeysym:
patPtr->detail.keySym = TkStringToKeysym(field);
So <1>
to <5>
are indeed special-cased as pointer device/mouse buttons. Sneaky.