Python 事件编码键盘输入

Python 事件编码键盘输入,python,raspberry-pi,event-handling,pygame,raspberry-pi3,Python,Raspberry Pi,Event Handling,Pygame,Raspberry Pi3,我在我的raspberry pi上用python编码。Python不是我最好的语言,所以请耐心听我说 我需要一个简单的代码来响应键盘上的按键。我会这样做,这样我可以设置脉冲宽度调制,但我不需要那个代码,我已经有了。我主要关心的是我正在努力理解我的任务所需的pygame功能 我希望能够键入一个键,如“向上箭头”↑ 并使程序输出“向上按”每按一毫秒向上箭头 伪代码如下所示: double x = 1 while x == 1: if input.key == K_UP: pr

我在我的raspberry pi上用python编码。Python不是我最好的语言,所以请耐心听我说

我需要一个简单的代码来响应键盘上的按键。我会这样做,这样我可以设置脉冲宽度调制,但我不需要那个代码,我已经有了。我主要关心的是我正在努力理解我的任务所需的
pygame
功能

我希望能够键入一个键,如“向上箭头”↑ 并使程序输出
“向上按”
每按一毫秒向上箭头

伪代码如下所示:

double x = 1
while x == 1:
    if input.key == K_UP:
        print("Up Arrow Pressed")
    if input.key == K_q
        x = 2
    wait 1ms

pygame.quit()

同样,由于不知道语法,我不知道要导入或调用什么↑ 按下以下键:

import pygame
pygame.init()

clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        print("Up Arrow Pressed")
    elif keys[pygame.K_q]:
        done = True

    clock.tick(1000)

pygame.quit()
请注意,这会将代码限制为每秒1000帧,因此不会完全等同于所需的1毫秒延迟。在我的电脑上,我只能看到大约600帧的帧速率

也许您应该查看“向下键”和“向上键”事件,然后切换输出

import pygame
pygame.init()

clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])

done = False
output = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                output = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                output = False
            elif event.key == pygame.K_q:
                done = True

    pygame.display.set_caption(f"Output Status {output}")
    clock.tick(60)

pygame.quit()
如果运行此操作,您将看到窗口的标题在↑ 按键被按下