It's the same with pyautogui, and keyboard. Just use the word for direction. For example, 'right', or 'left'. Like this:

import keyboard

keyboard.press_and_release('left') #presses left arrow key

I recommend looking at the documentation to find key codes, as to find the difference between arrows on the numpad and normal layout can be difficult, and just for general reference in the future.

Answer from 5rod on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do you capture arrow key presses?
r/learnpython on Reddit: How do you capture arrow key presses?
June 18, 2021 -

I want to trigger certain functions when pressing certain arrows, it must be captured without being in console and pressing enter each time.

edit: I found now that "left arrow" registers left arrow etc BUT it triggered hundreds of times when pressed

import keyboard
while True:
	if keyboard.is_pressed("left arrow"):
		print("mkay")

Everytime I press, it's very important that it only registeres once, any suggestions how to do that in an efficient manner?

I've got it working pretty good using sleep() efter each press but surely there must be a better way?

Discussions

Python keyboard library arrow keys problem - Stack Overflow
I was writing a script, which takes ... is that when I press the left keyboard arrow, also the number 4 is pressed. I can't find anything on google or in the documentation of the keyboard library. I am using Windows and Python 3.6.5... More on stackoverflow.com
๐ŸŒ stackoverflow.com
windows - How to track and simulate arrow keys through pynput in python - Stack Overflow
from pynput.keyboard import Key, ... press and release the left key. Hope I helped. ... Sign up to request clarification or add additional context in comments. ... In python, you can view enum values using the dir function. from pynput import keyboard print(dir(keyboard.Key)) # show full enum list... More on stackoverflow.com
๐ŸŒ stackoverflow.com
click - Python, check if arrow key pressed - Stack Overflow
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 pyga... More on stackoverflow.com
๐ŸŒ stackoverflow.com
input - Finding the Values of the Arrow Keys in Python: Why are they triples? - Stack Overflow
I am trying to find the values that my local system assigns to the arrow keys, specifically in Python. I am using the following script to do this: import sys,tty,termios class _Getch: def More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
PyAutoGUI
pyautogui.readthedocs.io โ€บ en โ€บ latest โ€บ keyboard.html
Keyboard Control Functions โ€” PyAutoGUI documentation
>>> pyautogui.keyDown('shift') ... pyautogui.keyUp('shift') # release the shift key ยท To press multiple keys similar to what write() does, pass a list of strings to press()....
๐ŸŒ
Quora
quora.com โ€บ In-Python-how-do-I-refer-to-keyboard-events-that-involve-the-arrow-keys-up-left-right-down
In Python, how do I refer to keyboard events that involve the arrow keys (up, left, right, down)? - Quora
Use key press and key release events supplied by the toolkit (KEYDOWN/KeyPress/on_key_down) and compare against the frameworkโ€™s arrow-key constants.
Top answer
1 of 3
4

The keyboard module has simple solutions for instances like these, they use event-triggered activation rather than polling as is used in your attempt.

example code:

import keyboard

def handleLeftKey(e):
    if keyboard.is_pressed("4"):
        print("left arrow was pressed w/ key 4")
        # work your magic

keyboard.on_press_key("left", handleLeftKey)
# self-explanitory: when the left key is pressed down then do something

keyboard.on_release_key("left", handleLeftKey02)
# also self-explanitory: when the left key is released then do something

# don't use both ...on_release & ...on_press or it will be
# triggered twice per key-use (1 up, 1 down)

Replace the code below and change it to suit your needs.

if __name__ == "__main__":
    while True:
        code = []
        try:
            for key in keys:
                if keyboard.is_pressed(key):
                    print(keyboard.key_to_scan_codes(key))
                    print(f"{key} pressed")
                    code.append(1)
                else:
                    code.append(0)

Another, more dynamic approach would look like:

import keyboard

keys = [
    "down",
    "up",
    "left",
    "right",
    "w",
    "s",
    "a",
    "d",
    "1",
    "2",
    "3",
    "4",
    "q",
    "e",
    "f"
]

def kbdCallback(e):
    found = False
    for key in keys:
        if key == keyboard.normalize_name(e.name):
            print(f"{key} was pressed")
            found = True
            # work your magic

    if found == True:
        if e.name == "left":
            if keyboard.is_pressed("4"):
                print("4 & left arrow were pressed together!")
                # work your magic

keyboard.on_press(kbdCallback)
# same as keyboard.on_press_key, but it does this for EVERY key

Another issue I noticed was that you were using "left arrow" when really it was recognized as "left" (at least on my system, it may be different on yours, but I assume you want it to work on all systems so it'd be safer using "left" instead)

The last method you could use is very statically typed and has no dynamic capabilities, but would work in the case of "4+left" or "left+4"

import keyboard

def left4trigger:
    print("the keys were pressed")

keyboard.add_hotkey("4+left", left4trigger)
# works as 4+left or left+4 (all of the examples do)

You seem smart enough to figure out the rest from there.

2 of 3
2

Beware, language may play a role! In my case the 'up' arrow was translated to my local language, you can run the following code to get the key value for your computer:

import keyboard    
def onkeypress(event):
    print(event.name)

keyboard.on_press(onkeypress)

#Use ctrl+c to stop
while True:
    pass
Find elsewhere
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 228595 โ€บ getting-an-input-from-arrow-keys
python - Getting an input from arrow keys. [SOLVED] | DaniWeb
It will constantly set the variable 'key', to whatever arrow key you press. If you wish to stop the background code at any time just do 'Break_KeyCheck = True' if you want to start it again do 'Break_KeyCheck = False'. I hope that helps. This also solves the issue, if you click on the screen it stops working.
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ user-input
User Input (Video) โ€“ Real Python
Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... In this lesson, youโ€™ll add user input to control your player sprite. Put this in your game loop right after the event handling loop. Watch for the level of indentation. This returns a dictionary containing the keys pressed at the beginning of every frame:
Published ย  March 17, 2020
๐ŸŒ
YouTube
youtube.com โ€บ codemore
how to use arrow keys in python - YouTube
Download this code from https://codegive.com Title: Using Arrow Keys in Python: A Tutorial with Code ExamplesIntroduction:Arrow keys play a crucial role in u...
Published ย  December 20, 2023
Views ย  594
Top answer
1 of 3
51

I think I figured it out.

I learned from here that each arrow key is represented by a unique ANSI escape code. Then I learned that the ANSI escape codes vary by system and application: in my terminal, hitting cat and pressing the up-arrow gives ^[[A, in C it seems to be \033[A, etc. The latter part, the [A, remains the same, but the code for the preceding Escape can be in hex(beginning with an x), octal (beginning with a 0), or decimal(no lead in number).

Then I opened the python console, and plugged in the triples I had previously received, trying to find their character values. As it turned out, chr(27) gave \x1b, chr(91) gave [, and calling chr on 65,66,67,68 returned A,B,C,D respectively. Then it was clear: \x1b was the escape-code!

Then I noted that an arrow key, in ANSI represented as a triple, is of course represented as three characters, so I needed to amend my code so as to read in three characters at a time. Here is the result:

import sys,tty,termios
class _Getch:
    def __call__(self):
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                ch = sys.stdin.read(3)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch

def get():
        inkey = _Getch()
        while(1):
                k=inkey()
                if k!='':break
        if k=='\x1b[A':
                print "up"
        elif k=='\x1b[B':
                print "down"
        elif k=='\x1b[C':
                print "right"
        elif k=='\x1b[D':
                print "left"
        else:
                print "not an arrow key!"

def main():
        for i in range(0,20):
                get()

if __name__=='__main__':
        main()
2 of 3
8

I am using Mac and I used the following code and it worked well: I got the values for my arrow keys as 0,1,2,3 (Up, Down, Left, Right): Always good to remember code 27 for ESC key too. Best regards!

while True:
    key = cv2.waitKey(1) & 0xFF

    # if the 'ESC' key is pressed, Quit
    if key == 27:
        quit()
    if key == 0:
        print "up"
    elif key == 1:
        print "down"
    elif key == 2:
        print "left"
    elif key == 3:
        print "right"
    # 255 is what the console returns when there is no key press...
    elif key != 255:
        print(key)
๐ŸŒ
pytz
pythonhosted.org โ€บ pynput โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.1.2 documentation
The PrintScreen key. This may be undefined for some platforms. ... A right arrow key.
๐ŸŒ
Wordpress
keepthinkup.wordpress.com โ€บ programming โ€บ python โ€บ python-turtle-handling-with-keypressarrow-key
Python turtle Handling with keypress(arrow key) โ€“ Freedom knows no bound
February 14, 2015 - Run the program and press the arrow key and see what happens. This is turtle handling with arrow keys : turtle handling Sample code: import turtle turtle.setup(400,500) wn = turtle.Screen() wn.title("Handling keypresses!") wn.bgcolor("lightgreen") tess = turtle.Turtle() def h1(): tess.forward(30) def h2(): tess.left(45) def h3(): tess.right(45) def h4(): wn.bye() wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q") wn.listen() wn.mainloop()
Top answer
1 of 1
8

There are different situations:

  • If you use a graphical frontend such as TKinter or PyGame, you can bind an event to the arrow key and wait for this event.

    Example in Tkinter taken from this answer:

    from Tkinter import *
    
    main = Tk()
    
    def leftKey(event):
        print "Left key pressed"
    
    def rightKey(event):
        print "Right key pressed"
    
    frame = Frame(main, width=100, height=100)
    main.bind('<Left>', leftKey)
    main.bind('<Right>', rightKey)
    frame.pack()
    main.mainloop()
    
  • If your application stays in the terminal, consider using curses as described in this answer

    Curses is designed for creating interfaces that run in terminal (under linux).

  • If you use curses, the content of the terminal will be cleared when you enter the application, and restored when you exit it. If you don't want this behavior, you can use a getch() wrapper, as described in this answer. Once you have initialized getch with getch = _Getch(), you can store the next input using key = getch()

As to how to call display() every second, it again depends on the situation, but if you work in a single process in a terminal, the process won't be able to call your display() function while it waits for an input. The solution is to use a different thread for the display() function, as in

import threading;

def display (): 
    threading.Timer(1., display).start ();
    print "display"

display ()

Here display schedules itself one second in the future each time it is called. You can of course put some conditions around this call so that the process stops when some conditions are met, in your case when an input has been given. Refer to this answer for a more thoughout discussion.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-arcade-handling-keyboard-input
Python Arcade โ€“ Handling Keyboard Input | GeeksforGeeks
September 23, 2021 - on_key_press(): This function will be called whenever a keyboard key is pressed. Inside this function, we will check if the key pressed is the up arrow key then we will print "upper arrow key is pressed".
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 1971803 โ€บ how-to-get-arrow-keys-input-in-python
How to get arrow keys input in python? | Sololearn: Learn to code for FREE!
Read this, to get an overwiew: https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal https://stackoverflow.com/questions/292095/polling-the-keyboard-detect-a-keypress-in-python ... Lothar I meant how to know if the user pressed up arrow key or down arrow key And respond to it accordingly.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ does the keyboard library work with arrow keys?
r/learnpython on Reddit: Does the keyboard library work with arrow keys?
December 14, 2023 -

I'm making a code to take a simulate a press key when a certain color is detected, now I've made the code up until I started to integrate the keyboard library.

Does the library work with arrow keys?

Since I'm not getting any response out of them unfortunately. Tried with other keys and functions and it works just fine.This is one of my snippets:

if right_arrow[0] == 176 and right_flag == 0: 
print("right") keyboard.press_and_release('right') 
right_flag = 1

Am I doing something wrong?

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to press keys with pyautogui?
r/learnpython on Reddit: How to press keys with pyautogui?
February 5, 2018 -

To be exact function and arrow type of keys. I am not even a beginners in Python but some how I ended up coming a small part of my project in Python, it will be really helpful if someone could provide with a cheat sheet for names to use to call actual keys, I found most of the key names and they are pretty same but I am unable to find the pyautogui name for the FUNCTION key.

๐ŸŒ
Talkerscode
talkerscode.com โ€บ howto โ€บ python-keyboard-input-arrow-keys.php
Python Keyboard Input Arrow Keys
Use the onkey() method to trigger the call of the up function, the down function, the left function, the right function, and the down function if the up, down, left, or right arrow keys are pressed, respectively.