Better way to deal with Tk's keyboard events mess for numpad keys in Python+tkinter?

╄→гoц情女王★ 提交于 2021-01-28 08:49:20

问题


I am making a tkinter application that responds to individual key presses on the numeric keypad. I find that handling the tk events for the numpad keypresses are a real pain because all platforms that I tried it on result in totally different events (windows, mac, linux), and the documentation I could find is either incomplete or just wrong. My main doc source is http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html

Only Linux seems "sane" and allows you to grab the tk keysym name such as "KP_Enter". Windows however requires you to either look at the keysym_num OR at the keycode depending on if you want to deal with NumLock on/off correctly, and still, can't seem to differentiate between some numpad keys and their normal equivalents (+/+, Enter/Return etc) OSX then, requires you to look at the keycode and those are totally different once again.

Example, the '0' key on the numpad:

  • Linux: event.keysym == 'KP_0'
  • Windows: event.keysym_num == 65379 or when Numlock is enabled: event.keycode == 96
  • Mac OS: event.keycode == 5374000

Am I missing something here, or is this really messy like this? Is there a better solution I overlook?


In my code I bound the keyup/down events on the main window:

class NumpadmadnessWindow(tkinter.Tk):
    def __init__(self):
        super().__init__()
        # ...
        self.bind("<KeyPress>", self.keypress)
        self.bind("<KeyRelease>", self.keyrelease)

And for debugging purposes my event handlers look like this:

    def keypress(self, event):
        print(time.time(), "KEYPRESS {char!r} keysym='{keysym}' keycode={keycode} keysym_num={keysym_num} state={state}".format(**vars(event))) 

    def keyrelease(self, event):
        print(time.time(), "KEYPRESS {char!r} keysym='{keysym}' keycode={keycode} keysym_num={keysym_num} state={state}".format(**vars(event))) 

Full code for a little runnable test application not really relevant I think, but can be found here: https://gist.github.com/irmen/2c9d6bb0afb16b464805410c108a2885

来源:https://stackoverflow.com/questions/45869902/better-way-to-deal-with-tks-keyboard-events-mess-for-numpad-keys-in-pythontkin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!