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

跟随《Python Crash Course》开发Alien Invasion遇Pygame显示错误求助

解决Pygame中"display Surface quit"错误(Alien Invasion游戏)

错误根源

你的代码里事件循环的退出判断逻辑写错了,这是导致pygame.error: display Surface quit的直接原因:

在run_game()方法的事件处理部分,你写了:

if event.type == pygame.quit():
    sys.exit()

这里的pygame.quit()是一个函数调用,它会立即关闭Pygame的所有底层资源(包括显示窗口和Surface),但主循环并没有立刻终止。当下一次循环执行到self.screen.fill()时,self.screen已经被销毁,因此抛出"display Surface quit"错误。

正确的写法应该是使用pygame.QUIT这个事件类型常量,它代表窗口关闭事件。

修正方案

修改run_game()中的事件处理代码:

def run_game(self):
    """Start the main loop for the game."""
    while True:
        # Watch for keyboard/mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # 改用事件类型常量
                pygame.quit()  # 先正确释放Pygame资源
                sys.exit()

        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.background_colour)
        self.ship.blit_me()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

额外注意事项

  1. 资源释放:退出前调用pygame.quit()是良好习惯,能确保Pygame的所有资源被正确清理。
  2. 图片路径检查:Ship类中的image_filepath = 'alien_invasion/assets/spaceship.jpg'可能存在路径问题。如果你的项目结构是:
    alien_invasion/
      ├─ alien_invasion.py
      ├─ settings.py
      ├─ ship.py
      └─ assets/
           └─ spaceship.jpg
    
    那么路径应该改为'assets/spaceship.jpg',否则会触发图片加载失败的错误(虽然这不是当前问题的原因,但后续会影响游戏运行)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:35:09