事件编码键盘输入
Event Coding Keyboard Input
我正在 raspberry pi 上用 python 编码。 Python 不是我最好的语言,所以请耐心等待。
我需要一个简单的代码来响应键盘上的击键。我这样做是为了设置脉冲宽度调制,但我不需要该代码,我已经有了它。我主要担心的是我很难理解我的任务所需的 pygame
功能。
我希望能够键入一个键,例如 "up arrow" ↑ 并让程序输出 "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()
同样,由于不知道语法,我不知道要导入或调用什么。
这里有一些代码可以检查 ↑ 键是否被按下:
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) 会将代码 限制为 每秒 one-thousand 帧,因此不会完全等于您想要的 1 毫秒延迟。在我的电脑上,我只能看到大约 six-hundred.
的帧率
也许您应该查看按键按下和按键事件,然后切换您的输出?
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()
如果你运行这个,你会看到 window 的标题在按下 ↑ 键时发生变化。
我正在 raspberry pi 上用 python 编码。 Python 不是我最好的语言,所以请耐心等待。
我需要一个简单的代码来响应键盘上的击键。我这样做是为了设置脉冲宽度调制,但我不需要该代码,我已经有了它。我主要担心的是我很难理解我的任务所需的 pygame
功能。
我希望能够键入一个键,例如 "up arrow" ↑ 并让程序输出 "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()
同样,由于不知道语法,我不知道要导入或调用什么。
这里有一些代码可以检查 ↑ 键是否被按下:
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) 会将代码 限制为 每秒 one-thousand 帧,因此不会完全等于您想要的 1 毫秒延迟。在我的电脑上,我只能看到大约 six-hundred.
的帧率也许您应该查看按键按下和按键事件,然后切换您的输出?
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()
如果你运行这个,你会看到 window 的标题在按下 ↑ 键时发生变化。