Python, check if arrow key pressed

Viewed 108

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()
4 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

You can use this code:

import keyboard
import time

while True:
   try:
        if keyboard.is_pressed('left'):
            print('You Pressed left!')
            time.sleep(0.1)
        if keyboard.is_pressed('right'):
            print('You Pressed right!')
            time.sleep(0.1)
        if keyboard.is_pressed('down'):
            print('You Pressed down!')
            time.sleep(0.1)
        if keyboard.is_pressed('up'):
            print('You Pressed up!')
            time.sleep(0.1)


except:
    break

By using listeners you will not have to play an infinite loop. Which I think is more elegant. This code will help you:

from pynput import keyboard
    
def on_press(key):
        if key == keyboard.Key.up:
            print('PRESSED')
        if key == keyboard.Key.esc:
            listener.stop()
    
    
with keyboard.Listener(on_press=on_press) as listener:
        listener.join()

Note that with 'keyboard.Key' you can detect the key that you want. You can even reproduce the case of holding two keys at the same time and detecting a combination!

This is the code I made, but it's only for a Pygame project with a window If you need the arrows in pygame I recommend this code:

from pygame.locals import *
import pygame
import sys

window_height = 100
window_width = 100

window = pygame.display.set_mode((window_width, window_height))
# This is the code to check if a player is pushing the arrows

while True:
    for evenement in pygame.event.get():
        if evenement.type == QUIT or (evenement.type == KEYDOWN and 
                                      evenement.key == K_ESCAPE):
            print('QUIT')
            pygame.quit()
            sys.exit()

        if evenement.type == KEYDOWN and evenement.key == K_RIGHT:
            print("Clicked on the right arrow")
        if evenement.type == KEYDOWN and evenement.key == K_LEFT:
            print("Clicked on the left arrow")
        if evenement.type == KEYDOWN and evenement.key == K_UP:
            print("Clicked on the up arrow")
        if evenement.type == KEYDOWN and evenement.key == K_DOWN:
            print("Clicked on the down arrow")
Related