Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, check if arrow key pressed

How to check if user presses an arrow key in python? I want something like this:

if right_key.pressed():
    do_some_shit()
elif left_key.pressed():
    do_other_stuff()

Update: I'm not using pygame, just need to detect key press

like image 431
Scott Avatar asked Oct 15 '25 18:10

Scott


1 Answers

In your terminal (or anacoonda prompt) run this command to install pynput library:

pip install pynput

And, in your editor

from pynput import keyboard
from pynput.keyboard import Key

def on_key_release(key):
    if key == Key.right:
        print("Right key clicked")
    elif key == Key.left:
        print("Left key clicked")
    elif key == Key.up:
        print("Up key clicked")
    elif key == Key.down:
        print("Down key clicked")
    elif key == Key.esc:
        exit()


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

More info

like image 133
Scott Avatar answered Oct 17 '25 08:10

Scott



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!