This Stack Overflow thread, Detect key press in python? had good examples. In your case because you want to detect only the first "KEY_DOWN" event you want to use on_press_key instead. Using your example it would look something like the following. import keyboard if __name__ == '__main__': keyboard.on_press_key("left arrow", lambda _: print('mkay')) while True: continue Answer from Jackkell100 on reddit.com
🌐
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?

🌐
PyAutoGUI
pyautogui.readthedocs.io › en › latest › keyboard.html
Keyboard Control Functions — PyAutoGUI documentation
>>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.keyUp('shift') # release the shift key
Discussions

How to simulate pressing the arrow down key when a specific element is present in the HTML using Selenium and Python - Stack Overflow
I want python to click on a key on my keyboard for example the arrow down key when a specific word for example google is present somewhere in the browser or in the searh bar. Is it possible with se... More on stackoverflow.com
🌐 stackoverflow.com
java - Python Selenium press down arrow to dispay all page contents - Stack Overflow
I have opened a web page using webdriver (selenium & python). All the items on the page do not load unless I press the space key 8 times or hold the down arrow. More on stackoverflow.com
🌐 stackoverflow.com
click - Python, check if arrow key pressed - Stack Overflow
from pygame.locals import * import ... evenement.type == KEYDOWN and evenement.key == K_DOWN: print("Clicked on the down arrow") ... import keyboard import time while True: try: if keyboard.is_pressed('left'): print('You Pressed left!') elif keyboard.is_pressed('right'): print('You ... More on stackoverflow.com
🌐 stackoverflow.com
May I virtualization a Down arrow key pre… - Apple Community
I create a python script using pynput LIB, running on python3. from pynput import keyboard from pynput.keyboard import Key, Controller keyb = Controller() is_alt_pressed = False is_shift_pressed = False is_down_pressed = False def on_press(key): global is_alt_pressed global is_shift_pressed ... More on discussions.apple.com
🌐 discussions.apple.com
November 21, 2021
🌐
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 2
1

Using Selenium to click on the Arrow Down key when a specific condition is met, as an example I have demonstrated through the following steps:

  • Open the url https://www.google.com/
  • Wait for the Google Home Page search box element i.e. By.NAME, "q" to be clickable.
  • Sends the character sequence selenium.
  • Wait for the auto suggestions to be visibile.
  • Click twice on Arrow Down key.

    • Code Block:

      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.keys import Keys
      
      options = webdriver.ChromeOptions() 
      options.add_argument("start-maximized")
      options.add_experimental_option("excludeSwitches", ["enable-automation"])
      options.add_experimental_option('useAutomationExtension', False)
      driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
      driver.get('https://www.google.com/')
      WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("Selenium")
      WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul[role='listbox'] li")))
      driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
      driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
      
    • Browser Snapshot:

PS: Implementing the above logic you can also click on Arrow Up, Arrow Left and Arrow Right keys.

2 of 2
1

you could search for the element with an xpath looking for the text you are searching e.g. $x('//*[.="Text"]') and then use sendKey() to press the key

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 228595 › getting-an-input-from-arrow-keys
python - Getting an input from arrow keys. [SOLVED] | DaniWeb
from msvcrt import getch from threading import Thread ### BACKGROUND CODE def KeyCheck(): global Break_KeyCheck Break_KeyCheck = False while Break_KeyCheck: base = getch() if base == '\xe0': sub = getch() if sub == 'H': key = 'UP_KEY' elif sub == 'M': key = 'RIGHT_KEY' elif sub == 'P': key = 'DOWN_KEY' elif sub == 'K': key = 'LEFT_KEY' Thread(target = KeyCheck).start() ### BACKGROUND CODE · It will constantly set the variable 'key', to whatever arrow key you press.
Find elsewhere
🌐
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.
🌐
Apple Community
discussions.apple.com › thread › 253390492
May I virtualization a Down arrow key pre… - Apple Community
November 21, 2021 - I create a python script using pynput LIB, running on python3. from pynput import keyboard from pynput.keyboard import Key, Controller keyb = Controller() is_alt_pressed = False is_shift_pressed = False is_down_pressed = False def on_press(key): global is_alt_pressed global is_shift_pressed global is_down_pressed if key == Key.shift_l: is_shift_pressed = True; if key == Key.alt_l: is_alt_pressed = True; if(is_shift_pressed and is_alt_pressed and (key == Key.up)): keyb.press(Key.down) is_down_pressed = True def on_release(key): global is_alt_pressed global is_shift_pressed global is_down_presse
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
python arrow control - Raspberry Pi Forums
To stop the car, press anything else. Do not hold keys down; just press them once. I think you are confused because you expect to hold the key down, and then release it to stop the maneuver. However a key-press as detected by curses is a single event. Holding the key down produces auto-repeat, and that has the effect of continually calling the maneuver, but with an uncertain delay.
🌐
IQCode
iqcode.com › code › python › pyautogui-down-arrow
pyautogui down arrow Code Example
March 22, 2022 - ess is not working for keys like enter in pyautogui name of home button in pyautogui how to use button like shift and ctrl using pyautogui in python pyautogui.press down arrow pyautogui down arrow how yo press ctrl + v in pyautogui hotkey pyautogui ctrl alt del pyautogui is key pressed pyautogui ...
🌐
Stack Overflow
stackoverflow.com › questions › 77951107 › im-having-problems-with-holding-down-the-arrow-keys-specifically-with-python
keyboard - I'm having problems with holding down the arrow keys specifically with python - Stack Overflow
What I'm trying to achieve is to be able to hold down the right arrow for 1 second every time the counter reaches 3. I checked if the codeblock actually runs with print, and it does. Please help me. Please note that I'm new to most python related stuff. ... import time import pyautogui import keyboard def hold_key(key, duration): keyboard.press(key) time.sleep(duration) keyboard.release(key) def main(): interval = 3 # seconds repeat_count = 3 right_arrow_duration = 1 default_key_duration = 1 counter = 0 while True: counter = counter + 1 # Hold "D" key for 2 seconds hold_key('d', default_key_duration) # Sleep for the specified interval time.sleep(interval) # Hold right arrow key for 0.5 seconds every 3 times if (counter == repeat_count): counter = 0 with pyautogui.hold('right'): # Here's the problem time.sleep(1) print("Right!"
🌐
STEMpedia
ai.thestempedia.com › home › python functions › iskeypressed()
iskeypressed() - Sensing Library - Python Function
July 25, 2022 - Pressing the up arrow key opens the gripper. Pressing the down arrow key closes the gripper.
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
🌐
Real Python
realpython.com › lessons › user-input
User Input (Video) – Real Python
Python · 29# Move the sprite based on user keypresses 30def update(self, pressed_keys): 31 if pressed_keys[K_UP]: 32 self.rect.move_ip(0, -5) 33 if pressed_keys[K_DOWN]: 34 self.rect.move_ip(0, 5) 35 if pressed_keys[K_LEFT]: 36 self.rect.move_ip(-5, 0) 37 if pressed_keys[K_RIGHT]: 38 self.rect.move_ip(5, 0) K_UP, K_DOWN, K_LEFT, and K_RIGHT correspond to the arrow keys on the keyboard.
Published   March 17, 2020
🌐
w3resource
w3resource.com › python-exercises › tkinter › python-tkinter-events-and-event-handling-exercise-12.php
Python Tkinter arrow key game - Character movement example
August 25, 2025 - self.canvas.bind("<Down>", self.move_down): Binds the down arrow key event to the move_down method. ... self.canvas.focus_set(): This line ensures that the canvas receives keyboard focus, allowing it to respond to arrow key presses.