I'd like to set up on_press_key binds using Python's Keyboard module through a For loop that's iteration through dictionary items. However, the binds do not seem to be assigned correctly.
Here's an example program I have written that demonstrates two ways I could bind. One is through a loop, and one is by manually doing it character by character:
import keyboard
import time
shortcuts = {
"Key1":"a",
"Key2":"b",
"Key3":"c",
}
def showText(text):
print(text)
for text, hotkey in shortcuts.items():
keyboard.on_press_key(hotkey, lambda _:showText(text))
keyboard.on_press_key("d", lambda _:showText("Key4"))
keyboard.on_press_key("e", lambda _:showText("Key5"))
while 1:
time.sleep(1)
The problem is the binds that are done through the loop return "Key3" instead of their respective keys. That is, if I were to press "a" or "b" or "c", it would print "Key3". But "d" returns "Key4" and "e" returns "Key5" as expected.
Why does the binding not work as expected inside the For loop? And is there a way to make it work? Binding each key manually is not only tedious but also opens up avenues for errors in case I update the dictionary later on.
Thank you