Python 按键和按键释放侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24352768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:27:54  来源:igfitidea点击:

Python Key press and Key Release Listener

pythonraspberry-pigpio

提问by Giridhar

I am controlling a remote toy car using python code .As of now the code is as below

我正在使用 python 代码控制遥控玩具车。截至目前,代码如下

def getkey():
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
        new[6][TERMIOS.VMIN] = 1
        new[6][TERMIOS.VTIME] = 0
        termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
        c = None
        try:
                c = os.read(fd, 1)
        finally:
                termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
        return c

def car():
    while True:
        key = getkey()
        if key == 's': #Down arrow
            print "Down"
            Backward()
        elif key == 'w': #Up arrow
            print "Up"
            forward()
        elif key == 'a': 
            print "left"
            Left()
        elif key == 'd': 
            print "Right"
            Right()
        elif key == 'q': #Quit
            print "That's It"
            break
def forward():
    GPIO.output(11,True)  #Move forward

When i press 'w' forward() method is called and the car moves forward but wont stop until i quit the program or call GPIO.output(11,Flase) from some other method.

当我按下 'w' forward() 方法被调用并且汽车向前移动但不会停止,直到我退出程序或从其他方法调用 GPIO.output(11,Flase) 。

Is there any key Listener which detects key release of any particular key .

是否有任何密钥侦听器可以检测任何特定密钥的密钥释放。

For example , if 'w' pressed called this method and if released call some other method

例如,如果 'w' 按下调用此方法,如果释放调用其他方法

Sudo code

须藤代码

if w_isPressed()
   forward()
else if w_isReleased()
    stop()

回答by famousgarkin

I've seen Pygamegame development library being successfully used in similar scenarios before, handling realtime systems and machinery in production, not just toy examples. I think it's a suitable candidate here too. Check out pygame.keymodule for what is possible to do with the keyboard input.

我之前已经看到Pygame游戏开发库成功地用于类似场景,处理生产中的实时系统和机器,而不仅仅是玩具示例。我认为这里也是一个合适的候选人。查看pygame.key模块以了解键盘输入可以做什么。

In short, if you are not familiar with game development, you basically continuously poll for events such as input state changes inside an 'infinite' game loop and react accordingly. Usually update the parameters of the system using deltas per time elapsed. There's plenty of tutorials on that and Pygame available around and Pygame docsare pretty solid.

简而言之,如果您不熟悉游戏开发,您基本上会不断轮询诸如“无​​限”游戏循环内的输入状态更改之类的事件并做出相应的反应。通常使用每经过一段时间的增量来更新系统的参数。有很多关于这方面的教程和 Pygame 可用,Pygame 文档非常可靠。

A simple example of how to go about it:

如何去做的一个简单例子:

import pygame

pygame.init()

# to spam the pygame.KEYDOWN event every 100ms while key being pressed
pygame.key.set_repeat(100, 100)

while 1:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                print 'go forward'
            if event.key == pygame.K_s:
                print 'go backward'
        if event.type == pygame.KEYUP:
            print 'stop'

You'll need to play with pygame.KEYDOWN, pygame.KEYUPand pygame.key.set_repeatdepending on how your car movement is implemented.

您需要使用pygame.KEYDOWN,pygame.KEYUPpygame.key.set_repeat取决于您的汽车运动是如何实现的。

回答by Eugene Terblanche

Faced a similar problem (I am no Python expert) but this worked for me

面临类似的问题(我不是 Python 专家)但这对我有用

import pynput
from pynput import keyboard 

def on_press(key):
    try:
        print('Key {0} pressed'.format(key.char))
        #Add your code to drive motor
    except AttributeError:
        print('Key {0} pressed'.format(key))
        #Add Code
def on_release(key):
    print('{0} released'.format(key))
    #Add your code to stop motor
    if key == keyboard.Key.esc:
        # Stop listener
        # Stop the Robot Code
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()