How to make a listener button in Python? Alya: pressed the CTRL -> function f () was executed
Windows / Python 3.6.0
How to make a listener button in Python? Alya: pressed the CTRL -> function f () was executed
Windows / Python 3.6.0
For example, pynput ( pip install pynput ). Example from official documentation:
from pynput import keyboard def on_press(key): try: print('alphanumeric key {0} pressed'.format(key.char)) except AttributeError: print('special key {0} pressed'.format(key)) def on_release(key): print('{0} released'.format(key)) if key == keyboard.Key.esc: # Stop listener return False # Collect events until released with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join() Eats any characters ( Fn+ , *.Lock ( NumLock , CapsLock ), Alt - whatever you like).
To stop listening you need to throw a StopException exception or return False from the handler. The on_press , on_release automatically executed not in the main thread.
As a bonus, you can additionally listen to mouse events.
You can use the standard msvcrt module.
import msvcrt, sys while True: pressedKey = msvcrt.getch() if pressedKey == 'q': sys.exit() else: print "Key:" + str(pressedKey) Pros: Present out of the box. Binding directly to msvcrt.
Cons: Alt, Ctrl, Shift and all * Lock buttons are not caught. Does not work in all environments. I did not work in PyCharm and GitBash (for a long time I didn’t understand what was going on until I thought of running in powershell)
Source: https://ru.stackoverflow.com/questions/654733/
All Articles