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

Python小游戏无法退出问题求助(附Pygame代码)

Pygame程序无法退出的解决方案

你的代码核心问题在于主循环的条件设置错误,导致捕获到退出事件后无法终止循环:

  • 当前用while True创建了一个无限循环,即便把running设为False,循环也不会停止
  • pygame.display.update()和pygame.quit()放在循环外部,永远不会被执行到

修改方案很简单:

  • 将主循环的条件改为while running:,这样当running变为False时,循环会正常终止
  • 把pygame.display.update()移到循环内部(这是Pygame主循环的标准写法,确保画面能正常更新)

修改后的完整代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pygame  # importation bibliotheque pygame
from pygame.locals import *  # importation de tout les modules de pygame

pygame.init()  # initialisation du module
fen = pygame.display.set_mode((800, 600))  # variable fenetre stockant les valeurs ouvrant cette fenetre en 800 sur 600
pygame.mixer.music.load(r"C:\Users\namik\Music\02 Chun Li.mp3")  # outil de pygame chargeant ma musique
pygame.mixer.music.play()  # lance musique au démarrage du programme
pygame.display.set_caption('clic souris')

running = True  # attribution de la valeur Vrai a running

while running:  # 用running作为循环条件
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
    pygame.display.update()  # 移到循环内

pygame.quit()

另外补充:你也可以在捕获QUIT事件时直接调用pygame.quit()和sys.exit(),不过用running变量控制循环是更规范的写法,方便后续扩展其他退出逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:52:45