Pygame程序按Q键无法正常退出,添加事件循环后恢复正常,求原因
Let's break down exactly why this happens—it all boils down to how Pygame interacts with your operating system's event system.
The Core Issue: Unprocessed Event Queues
When you run a Pygame program, your operating system sends constant events to the app (things like key presses, window move requests, or the "close window" signal). Pygame stores these events in an event queue, and your program needs to regularly clear or process this queue to stay in sync with the OS.
If you never call pygame.event.get() (or the simpler pygame.event.pump()), two critical problems occur:
- Your OS thinks the program is unresponsive: Since Pygame isn't acknowledging the OS's events, the system marks your app as frozen—even though your loop is still running in the background.
pygame.key.get_pressed()fails to register key presses: Whileget_pressed()technically queries the keyboard's raw state, Pygame relies on processing the event queue to sync that state correctly. Without emptying the queue, the key press for Q never gets properly registered, so yourif keys[pygame.K_q]check never triggers.
Why Uncommenting the Event Loop Fixes It
When you uncomment those three lines:
for event in pygame.event.get(): if event.type == pygame.QUIT: run=False
You're doing more than just handling the QUIT event—you're clearing the entire event queue each loop iteration. This lets Pygame communicate with the OS properly, keeps your window responsive, and ensures that pygame.key.get_pressed() receives accurate updates about which keys are pressed. Even if you didn't handle the QUIT event, just calling pygame.event.get() would be enough to make your Q key exit work.
A Quick Alternative
If you don't need to handle specific events but still want to keep your program responsive, you can replace the event loop with a simple call to pygame.event.pump():
while run==True: pygame.time.delay(16) pygame.event.pump() # Process OS events keys=pygame.key.get_pressed() win.fill((125,125,125)) if keys[pygame.K_q]: run=False pygame.display.update()
This tells Pygame to process all pending OS events without clearing the queue, which is sufficient to keep your key presses working and your window from freezing.
内容的提问来源于stack exchange,提问作者RedSubmarine




