如何在不关闭tkinter的情况下关闭pygame?
我正在尝试使用Tkinter来接收文本输入,然后用这个输入来运行Pygame做动画。不过,当我关闭Pygame的时候,出现了一个错误。
这是我计划使用Pygame的一个简化版本:
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()
Pygame可以正常打开并运行得很好,但当我关闭它时就出现了这个错误:
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就崩溃了。
1 个回答
0
你想用 sys.exit()
来退出 pygame 的主循环,但这样会把整个程序都退出,包括你之前启动的 tkinter 界面。你应该用一个条件来退出 pygame 的主循环,也就是那个唯一的 while
循环。比如:
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
running = False
...