Search code examples
pythonpython-3.xtkinterpynput

Detect a key press and show it in a label tkinter


Im using tkinter and pynput. I have a button to select a trigger key after the user press the key I want to show the ord of the pressed key in a label this is the error: ord() expected string of length 1, but KeyCode found and here is the code:

TriggerKey = Button(win, text = "Set a trigger key", command = Key_listener)
TriggerKey.place(x = 70, y = 70,)

This is the Listen function:

def Key_listener():
    with Listener (on_press=trigger_Key, on_release=release) as trigger:
        trigger.join()

and here is where I think the problem is:

def trigger_Key(Key):
    TriggerKey = Key
    print(TriggerKey) #prints the pressed button for a test
    ord_key = ord(TriggerKey)
    trigger_key_label.config(text= ord_key)

Solution

  • If you used it with tkinter,it will block your code. Change your function Key_listener:

    def Key_listener():
        trigger = Listener (on_press=trigger_Key, on_release=release)
        trigger.start()
    

    About your error: in the trigger_Key,key is a Keycode function.You need to use ord(Key.char).