【问题标题】:Event Coding Keyboard Input事件编码键盘输入
【发布时间】:2018-06-04 22:26:12
【问题描述】:
我在我的树莓派上使用 python 进行编码。 Python 不是我最好的语言,所以请耐心等待。
我需要一个简单的代码来响应键盘上的击键。我这样做是为了设置脉冲宽度调制,但我不需要那个代码,我已经有了。我主要担心的是我很难理解我的任务所需的pygame 功能。
我希望能够键入一个键,例如“向上箭头”↑,并让程序在按下向上箭头的每一毫秒输出"up pressed"。
伪代码如下所示:
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()
由于不知道语法,我不知道要导入或调用什么。
【问题讨论】:
标签:
python
raspberry-pi
event-handling
pygame
raspberry-pi3
【解决方案1】:
这里有一些代码会检查是否按下了 ↑ 键:
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()
请注意,clock.tick(1000) 会将代码限制为每秒一千帧,因此不会完全等同于您想要的 1 毫秒延迟。在我的 PC 上,我只能看到大约 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()
如果你运行它,你会看到在按下 ↑ 键时窗口的标题会发生变化。