0

所以我尝试使用 Tkinter 接收文本输入,然后从中运行 pygames 来制作动画。但是当我关闭 Pygames 时出现错误。

我计划如何使用 Pygames 的简化版本:

def the_program():
    if spot.get().strip() == "":
        tkMessageBox.showerror("X", "Y")
    else:
        code = spot.get().strip()
        pygame.init()
        pygame.display.set_caption('X')
        windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            pygame.display.update()

运行 Tkinter:

root = Tk()
frame = Frame(root)
text = Label(frame, text='X')
spot = Entry(frame)
button = Button(frame, text = 'Ready?', command = the_program) "Starts Pygames"
frame.pack()
text.pack()
spot.pack()
button.pack()

root.mainloop()

Pygames 可以正常打开并且运行良好,但是当我关闭它时会出现以下错误:

Traceback (most recent call last):
  File "C:\Python26\Practice\legit Battle Master.py", line 82, in <module>
    root.mainloop()
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1017, in mainloop
    self.tk.mainloop(n)
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1412, in __call__
    raise SystemExit, msg

我怎样才能避免这种情况?我尝试删除“sys.exit()”,但 python 崩溃了。

4

1 回答 1

0

您正在尝试使用 退出 pygame 主循环sys.exit(),这会退出整个正在运行的应用程序,包括您在 pygame 之前启动的 tkinter GUI。您应该使用条件退出 pygame 主循环(唯一的while子句)。例如:

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            running = False
...
于 2011-05-12T20:20:47.560 回答