22

我刚刚花了相当多的时间找到一个 64 位的 pygame 安装以与 python 3.3 一起使用,(在这里),现在我正在尝试制作一个窗口。然而,虽然窗口打开得很好,但它在点击 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 可能会进入其中一个循环,但即使解决了这个问题,我也更希望能够在我想要的时候关闭窗口。

4

9 回答 9

32

大多数 pygame 教程似乎建议通过调用pygame.quit()然后退出sys.exit()。我个人遇到了问题(虽然是在 unix 系统上),但仍然没有正确关闭窗口。pygame.display.quit()解决方案是在之前专门添加pygame.quit(). 据我所知,这不应该是必要的,恐怕我不知道为什么这解决了这个问题,但它确实解决了。

于 2014-10-12T08:59:44.953 回答
18

如果要在按下窗口按钮 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() 关闭该窗口。

于 2015-12-03T03:52:58.747 回答
8

不确定但试试这个 因为你的代码在我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 主循环没有相互理解。
不过,您的代码将在命令提示符下运行得很好。

于 2013-11-09T20:33:59.683 回答
4

这是在 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 中修复

于 2019-05-12T01:10:33.563 回答
1

在顶部添加:

import sys

在需要退出的地方添加:

if event.type == pygame.QUIT:
    pygame.quit()
    sys.exit()
于 2021-02-23T14:31:05.927 回答
1

在 IDE (Spyder 3.3.6) 中运行 Python 3.7.4 时遇到了同样的问题。在我的情况下, pygame.quit() 不会完全关闭程序。尽管如此,添加 quit() 或 exit() 对我有用!

于 2020-02-27T20:45:05.897 回答
0

尝试使用以下命令:

sys.exit(0)

注意:您需要导入 sys 库才能使用它。

于 2015-05-30T13:32:09.867 回答
0

The IDE interferes with how pygame runs the code. Try to run it from the commandline or the terminal. The problem should disappear.

于 2017-12-29T23:47:19.697 回答
-2

要回答原始问题:您必须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()
于 2018-12-11T00:52:29.713 回答