2011-05-12 102 views
0

所以我想用Tkinter來接收文本輸入,然後從那裏運行pygames來做動畫。當我關閉Pygames時,我得到一個錯誤。如何在不關閉tkinter的情況下關閉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崩潰。

+1

選擇所有的行源代碼,然後按CTRL + K創造更好的語法高亮和代碼格式化,請:) – Constantinius 2011-05-12 20:15:21

回答

0

您正試圖從012g退出pygame主循環,它將退出整個正在運行的應用程序,包括您在pygame之前啓動的tkinter GUI。您應該使用條件退出pygame主循環(唯一的while子句)。 e.g:

running = True 
while running: 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      running = False 
... 
+0

同樣的事情發生,當我刪除sys.exit()。崩潰窗口打開,說pythonw.exe遇到問題等。 – Ron 2011-05-12 20:25:25

+0

也許你必須在你的Tkinter程序結束時調用pygame.quit()。 – Constantinius 2011-05-12 20:27:21

+0

崩潰來自我修復的程序中的另一個問題。感謝您的幫助,現在可以工作。 – Ron 2011-05-12 20:44:09

相關問題