Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect key release with python ( not keypress)?

How can I detect key release with python 3 ?

Like if I pressed the key a for 1 second , when I remove my finger from the key ( releasing the key ) , It will print("Key 'a' pressed then released").

I trying to do it with module keyboard but I have no idea about how to use it for this. I used to detect keypress with it.
msvcrt module don't work for me but if msvcrt can do what I want , then you can answer me.

Note:

I Don't want to use Pygame or any other module which will show pop-ups

like image 634
Black Thunder Avatar asked Aug 18 '26 00:08

Black Thunder


1 Answers

You can use the pynput module:

from pynput import keyboard

def on_key_release(key):
    print('Released Key %s' % key)

with keyboard.Listener(on_release = on_key_release) as listener:
    listener.join()

According to the documentation of pynput keyboard listener is a thread, which calls the function specified on on_release with the key argument. You can also specify a on_press function.

Edit:

As asked in discussions, you can stop the listener by returning false from the on_key_release function. Like that:

def on_key_release(key):
    print('Released Key %s' % key)
    return False
like image 126
Franz Forstmayr Avatar answered Aug 20 '26 17:08

Franz Forstmayr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!