How to detect key press event and key hold down event without using pygame

Viewed 9503

I am currently looking for a library that is able to detect/monitor the keyboard. My intention is to detect when a key is being held down and while it occurs something should happen.

Most SO posts suggest to use pygame, but i find it a bit too much, to involve a library such as that for this simple task. i've also tried with pynput, which resulted only detecting one press rather than a stream of presses.

any suggestions on how i can make this while loop detect a key is being pressed / held down...

My attempt with while loop:

from pynput import keyboard

def on_press(key):
    while key == keyboard.Key.cmd_l:
        try:
            print('- Started recording -'.format(key))
        except IOError:
            print "Error"
    else:
        print('incorrect character {0}, press cmd_l'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False



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

The while solution make it stuck in the while loop, making it impossible to get out of it.

2 Answers

it's actually really simple. just a few lines of code, and its done!

from turtle import *

def a():
    print("key is pressed!")
    forward(5)

def b():
    print("key is not pressed!")
    backward(30)

listen()
onkeypress(a," ")
onkeyrelease(b," ")

you can replace " " with any key of your choice, surrounded in "" examples: "a","h","e","Up","y"

Related