首页 > 解决方案 > pygame.error: 显示 Surface 退出 - 为什么会这样?

问题描述

经过数小时的研究,我无法弄清楚为什么会触发此错误。这是整个消息:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "snake.py", line 37, in <module>
    redraw_window()
  File "snake.py", line 23, in redraw_window
    win.fill((0, 0, 0))
pygame.error: display Surface quit

当我运行程序时,窗口会立即打开和关闭。我正在通过 conda 虚拟环境运行 Python v3.7。这是我的代码:

import pygame
pygame.init()

#----------------------------
# CONSTANTS
#----------------------------

window_width = 256
window_height = 256

win = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')

#----------------------------
# CLASSES
#----------------------------

#----------------------------
# REDRAW WINDOW
#----------------------------

def redraw_window():
    win.fill((0, 0, 0))
    pygame.display.update()

#----------------------------
# MAIN GAME LOOP
#----------------------------
running = True
while running:

    # listen for window closure
    for event in pygame.event.get():
        if event.type == pygame.quit():
            run = False

    redraw_window()

pygame.quit()

我什至尝试将“win”传递给 redraw_window 函数,但这并没有改变。

标签: pythonpygame

解决方案


pygame.quit()是一个函数并取消初始化所有 PyGame 模块。当你这样做

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

该函数被调用并且所有 PyGame 模块都未初始化。

object的type属性pygame.event.Event()表示事件的类型。您需要将事件类型与标识事件的枚举常量进行比较。退出事件由pygame.QUIT(参见pygame.event模块)标识:

因此,您必须与pygame.QUIT而不是竞争pygame.quit()

running = True
while running:

    # listen for window closure
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    redraw_window()

pygame.quit()

推荐阅读