Pygame错误:显示表面退出:为什么?
有没有人能告诉我,为什么我的应用程序会出现以下错误并退出:
pygame错误:显示界面已退出。
10 个回答
6
把 if event.type == pygame.quit():
替换成 if event.type == pygame.QUIT:
。
6
我在一段非常简单的代码中遇到了类似的问题:
import sys, pygame
pygame.init()
size = width, height = 640, 480
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("Golfball.png")
ballrect = ball.get_rect()
while 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
pygame.time.delay(5)
错误信息是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bounce.py", line 22, in <module>
screen.fill(black)
pygame.error: display Surface quit
所以我在
import pdb
之后加了
pygame.init()
并在
pdb.set_trace()
那一行之后使用了
pygame.quit()
现在我运行程序,点击关闭窗口,结果有点意外地发现我进入了调试器(毕竟,我原本以为退出会立刻让我完全退出)。所以我得出结论,quit并没有在那个时候完全停止所有东西。看起来程序在退出之后还在继续,达到了
screen.fill(black)
这导致了问题。 所以我在
break
之后加了
pygame.quit()
现在一切都正常运行了。
[ 后来补充:我现在意识到
pygame.quit()
是退出模块,而不是正在运行的程序,所以你需要break来退出这个简单的程序。]
仅供参考,这意味着好的版本是
import sys, pygame
pygame.init()
size = width, height = 640, 480
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("Golfball.png")
ballrect = ball.get_rect()
while 1:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
break
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
pygame.time.delay(5)
11
我遇到过类似的问题,发现Surface对象不太喜欢被深拷贝。当我对这样的对象使用copy.deepcopy()进行拷贝,然后访问这个拷贝时,出现了奇怪的错误信息(而且我并没有调用pygame.quit())。也许你也遇到过类似的情况?