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

添加clock.tick后Pygame窗口无法正常关闭的问题

Pygame窗口无法正常关闭的修复方案

问题根源

你的代码里有两个关键问题导致窗口关闭响应异常:

  1. 事件处理被阻塞:内部的while timer > screen.fixed_fps循环会反复执行fixed_update(),这段时间里完全没处理事件队列,导致点击关闭按钮的QUIT事件无法被及时捕获。
  2. 事件处理时机滞后:即使跳出内部循环,事件处理也放在了update()之后,进一步延迟了对窗口操作的响应。

修复后的代码

把事件处理移到主循环最开头,确保每次循环优先响应事件;同时可以在固定步长更新的内部循环里也加入事件检查,彻底避免长时间阻塞:

def game_loop():
    """The main game loop that runs as the game runs. Returns when the pygame window is closed."""
    global running
    global timer
    while running:
        # 先处理所有事件,保证窗口操作第一时间响应
        for event in pygame.event.get():  
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                return
        
        # 固定步长更新循环,加入事件检查防止长时间阻塞
        while timer > screen.fixed_fps:
            fixed_update()
            timer -= screen.fixed_fps
            # 检查事件,避免固定更新次数过多时卡住
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                    return
        
        update()
        # 直接用tick的返回值作为增量,确保单位匹配(毫秒)
        delta = screen.clock.tick(screen.fps)
        timer += delta
    pygame.quit()
    return

额外提醒

  • 注意timer和screen.fixed_fps的单位统一:如果fixed_fps是按单帧毫秒数设置(比如60帧对应16.67),clock.tick()返回的正好是毫秒数,直接用它累加就对了,不用额外的delta_time()函数。
  • 触发关闭时直接调用pygame.quit()并返回,避免后续无效代码执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:35:28