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
CodePudding user response:
@Aommaster I don't know if it's a bug in python or something.
Instead of keyboard.on_press_key(hotkey, lambda _:showText(text))
in the loop you can make a function and call the function inside the loop, Then, It works perfectly.
import keyboard
import time
shortcuts = {
"Key1":"a",
"Key2":"b",
"Key3":"c",
}
def showText(text):
print(text)
def bind_key(hotkey,text):
keyboard.on_press_key(hotkey, lambda _:showText(text))
for text, hotkey in shortcuts.items():
bind_key(hotkey,text)
keyboard.on_press_key("d", lambda _:showText("Key4"))
keyboard.on_press_key("e", lambda _:showText("Key5"))
# you can also call these using function.
# bind_key("d","Key4")
# bind_key("e","Key5")
while 1:
time.sleep(1)