Closed WanliZhong closed 1 year ago
I use while true
loop and keyboard.read_event()
to solve my problem.
So I had this exact same issue so I did some digging and it's because of how keyboard
stores the information internally.
The solution in the follow up comment wasn't going to work for me due to how I was using keyboard
, but I found another solution which is more robust, but basically requires just using keyboard.hook
and not using on_press_key
or on_release_key
at all and rolling your own as follows:
import keyboard
import time
def press_func():
print("pressed a key!")
def release_func():
print("released a key!")
press = keyboard.hook(lambda e: e.name == "space" and e.event_type == "down" and press_func())
release = keyboard.hook(lambda e: e.name == "space" and e.event_type == "up" and release_func())
while True:
time.sleep(5)
break
print("UNHOOKING PRESS")
keyboard.unhook_key(press)
print("UNHOOKING RELEASE")
keyboard.unhook_key(release)
while True:
time.sleep(5)
break
In the above I am binding both to the space bar key as you can see. This is basically what is happening in the on_press_key
except it uses hook_key
internally which seems to have issues when you bind two things to the same key (one up, one down)
Anyway, hope this may be useful to anyone else out there who comes across this issue!
When I run the code below, I can't unhook these two event. I only can unhook one of them, but the another will work still.
This is the error thrown by the code: