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 OverflowIt'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.
You can use the below code snippet to access the arrow keys. I have made use of the keyboard library inorder to do that.
- UP ARROW KEY -> "up"
- DOWN ARROW KEY -> "down"
- LEFT ARROW KEY -> "left"
- RIGHT ARROW KEY -> "right"
Here is a sample code
import keyboard
# To Press UP ARROW KEY
keyboard.press("up")
Hope it helps!!!
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?
Python keyboard library arrow keys problem - Stack Overflow
windows - How to track and simulate arrow keys through pynput in python - Stack Overflow
click - Python, check if arrow key pressed - Stack Overflow
input - Finding the Values of the Arrow Keys in Python: Why are they triples? - Stack Overflow
Videos
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.
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
How to press all four of those keys:
from pynput.keyboard import Key, Controller
kb = Controller()
kb.press(Key.up) # Presses "up" key
kb.release(Key.up) # Releases "up" key
kb.press(Key.left) # Presses "left" key
kb.release(Key.left) #etc..
kb.press(Key.right)
kb.release(Key.right)
kb.press(Key.down)
kb.release(Key.down)
You can make it easier by creating a function if you need use it many times:
from pynput.keyboard import Key, Controller
kb = Controller()
def press(button):
kb.press(button)
kb.release(button)
# Then you can use it in one line:
press(Key.left)
# It will automatically press and release the left key.
Hope I helped.
In python, you can view enum values using the dir function.
from pynput import keyboard
print(dir(keyboard.Key)) # show full enum list
Output
['__class__', '__doc__', '__members__', '__module__', 'alt', 'alt_l', 'alt_r',
'backspace', 'caps_lock', 'cmd', 'cmd_r', 'ctrl', 'ctrl_l', 'ctrl_r', 'delete',
'down', 'end', 'enter', 'esc', 'f1', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15',
'f16', 'f17', 'f18', 'f19', 'f2', 'f20', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9',
'home', 'insert', 'left', 'media_next', 'media_play_pause', 'media_previous',
'media_volume_down', 'media_volume_mute', 'media_volume_up', 'menu', 'num_lock',
'page_down', 'page_up', 'pause', 'print_screen', 'right', 'scroll_lock', 'shift',
'shift_r', 'space', 'tab', 'up']
You can see up, down, left, right in the list. Try those keys.
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
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!
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()
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)
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 = 1Am I doing something wrong?
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.