python - 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 函数,但这并没有改变。
解决方案
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()
推荐阅读
- android - 如何将此导航抽屉图标更改为使活动返回另一个活动的后退箭头
- java - spring boot 中有什么方法可以控制关机机制吗?
- windows - 如何通过代码“关闭密码保护共享”
- python - 如何改进和扩展我的应用程序开发工作流程?
- c++ - 如何在 VS 2017 中创建协程
- vuejs2 - 如何在 Vue-timepicker 中设置时间限制?
- php - Wordpress:“wp-admin-canonical”获取错误的 URL,导致 wp-admin 中的链接使用根目录而不是子目录
- excel - 偏移功能无法删除除标题之外的所有可见单元格
- c - 为什么我的 fork() 不分叉一个孩子并输出打印语句?
- python - 将字符串与空格进行比较时,Python中的字符串标识等价