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

不羁岁月 提交于 2019-12-03 20:48:33

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.*)

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"

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