You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Pygame代码中break无法退出循环,run=False却可行?

为什么Pygame里用break无法退出程序?

先看你写的代码:

import pygame

pygame.init()

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))


run = True
while run:
    for event in pygame.event.get():
        print(event)
        
        if event.type == pygame.QUIT:
            break
            
pygame.quit()    

问题出在break的作用范围:你写的break只能终止内层的for event in pygame.event.get()循环,外层的while run循环完全不受影响。当你点击退出按钮触发QUIT事件时,break跳出for循环后,程序立刻回到while循环的开头,再次执行事件获取的for循环——如果此时没有新事件,for循环直接走完,然后继续绕着while循环转,程序自然退不出去。

要退出程序,得让外层的while循环终止,所以正确的做法是把run设为False,这样下一次while循环的条件run == True不成立,整个循环就结束了,接着执行pygame.quit()完成退出。

修改后的代码示例:

import pygame

pygame.init()

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

run = True
while run:
    for event in pygame.event.get():
        print(event)
        
        if event.type == pygame.QUIT:
            run = False
            break  # 可选:提前结束内层事件循环,不写也能退出,只是多走一次循环
            
pygame.quit()    

内容的提问来源于stack exchange,提问作者David Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:16:58