import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
我是python和pygame的新手,只是试图测试keydown事件但它不起作用....请帮助!
答案 0 :(得分:1)
You need to set up some display properties before you can use keyboard events. No window, no key events. So add something like this before the while
loop and it should work:
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
Normally, you'd also set up a clock using clock = pygame.time.Clock()
, frames per second used in clock.tick(frames_per_second)
, some objects/players/rects etc. before the loop but I'll leave that to you.
Here's your code with a bare minimum display setup that'll enable key events:
import pygame
pygame.init()
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this DOES work! :)')
答案 1 :(得分:0)
因为Pygame只能在Python v3.2上运行,在下面运行,所以我现在无法测试它。
但是,如果我不完全脱离我的药物,我认为这是因为你没有更新显示器。
考虑这一变化:
import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
pygame.display.flip()
这将更新显示并触发显示中发生的事件 如果你不这样做,你最终会得到一个陈旧的窗口,除了初始渲染之外,它不会触发,渲染或生成任何东西。
同样,在许多GL库中,您需要清空事件缓冲区,否则会产生相同的效果。这意味着你最终会得到一个只是“挂起”的陈旧窗口,因为事件试图“进入”缓冲区,但你不会定期清空它。 (有些图形库甚至要求你轮询事件池,即使它是空的只是为了“释放”事件队列。)
因此在使用图形时请记住: