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

こ雲淡風輕ζ 提交于 2019-12-21 06:19:28

问题


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.


回答1:


One of the simplest way I found is to use pynput module.can be found here with nice examples as well

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

Collect events until released

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

above is the example worked out for me and to install, go

sudo pip install pynput (pip3 if python3.*)



回答2:


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"



来源:https://stackoverflow.com/questions/44903210/how-to-detect-key-press-event-and-key-hold-down-event-without-using-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!