Python无法退出Pygame游戏[重复]
原文标题 :Python Cant exit a Pygame game [duplicate]
我刚刚花了相当多的时间找到一个 64 位安装的 pygame 以与 python 3.3 一起使用,(here),现在我正在尝试制作一个窗口。但是,虽然窗口打开得很好,但它在点击时并没有关闭x 按钮。实际上,我必须关闭 IDLE 才能关闭窗口。我正在运行 64 位版本的 Win 7。这是我的代码:
import pygame
import time
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
pygame.display.set_caption("Hello World")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
当我附加
time.sleep(5)
pygame.quit()
它仍然没有关闭。我唯一的猜测是 pygame.quit 可能会进入其中一个循环,但即使解决了这个问题,我也更希望能够在我想要的时候关闭窗口。
回复
我来回复-
Erikun 评论
大多数 pygame 教程似乎建议通过调用
pygame.quit()
然后sys.exit()
退出。我个人遇到了问题(虽然是在 unix 系统上),但仍然没有正确关闭窗口。解决办法是在pygame.quit()
之前加pygame.display.quit()
。据我所知,这不应该是必要的,恐怕我不知道为什么这解决了这个问题,但它确实解决了。2年前 -
jerryalfs 评论
如果要在按下窗口按钮 x 时关闭 pygame,请输入如下代码:
from sys import exit while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit()
我们将 exit() 放在 pygame.quit() 之后,因为 pygame.quit() 使系统退出,而 exit() 关闭该窗口。
2年前 -
xor 评论
不确定,但试试这个 因为在我最后添加
pygame.quit()
后,你的代码在我的系统上运行良好import pygame import time (width, height) = (300, 200) screen = pygame.display.set_mode((width, height)) pygame.display.flip() pygame.display.set_caption("Hello World") running = True try: while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() except SystemExit: pygame.quit()
这可能是因为 Idle 是在 Tkinter 上制作的,因此 Tkinter 和 Pygame 主循环没有相互理解。
不过,您的代码将在命令提示符下运行得很好。2年前 -
blissweb 评论
这是在 OSX 上为我工作的最终代码,同时让内核在 Jupyter 上保持活跃。编辑 – 它有时仍然会使内核崩溃:-(
running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.quit() pygame.quit() exit()
还需要降级 ipython 以消除一些神奇的别名警告消息,使用:
conda install ipython=7.2.0
显然该问题将在 ipython 7.6.0 中修复
2年前 -
Jose Pablo Jimenez 评论
在 IDE (Spyder 3.3.6) 中运行 Python 3.7.4 时遇到了同样的问题。在我的情况下 pygame.quit() 不会完全关闭程序。尽管如此,添加 quit() 或 exit() 确实骗我!
2年前 -
FortCraftCoder 评论
在顶部添加:
import sys
在需要退出的地方添加:
if event.type == pygame.QUIT: pygame.quit() sys.exit()
2年前 -
OphirBack 评论
尝试使用以下命令:
sys.exit(0)
注意:您需要导入 sys 库才能使用它。
2年前 -
NinjasAtWork 评论
IDE 会干扰 pygame 运行代码的方式。尝试从命令行或终端运行它。问题应该消失。
2年前 -
Bruno Cavalleri 评论
要回答原始问题:您必须在打破主循环后调用
pygame.quit()
。一种优雅的解决方案如下:def run(): pygame.init() while True: # ... for event in pygame.event.get(): # Handle other events if event.type == pygame.QUIT: return pygame.quit()
2年前