2016-07-30 62 views
0

我想創建一個顯示消息的GUI,並且它會在一段時間後自動銷燬。我在不同的帖子中看到了這個問題,但沒有提出任何解決方案爲我的應用程序。下面的代碼一段時間後關閉tkinter GUI

class MessageShort(tkSimpleDialog.Dialog): 

def __init__(self, parent, text, time): 


    self.top=Toplevel.__init__(self, parent) 
    self.transient(parent) 
    self.parent = parent 
    self.text=text 
    self.time=time 
    body = Frame(self) 
    self.initial_focus = self.body(body) 
    body.pack(padx=10, pady=10) 
    if not self.initial_focus: 
     self.initial_focus = self 
    self.geometry("+%d+%d" % (parent.winfo_rootx()+200, 
           parent.winfo_rooty()+75)) 
    self.initial_focus.focus_set() 
    self.wait_window(self) 

def body(self, master): 
    m=Message(master, text=self.text).grid(row=0,column=0,sticky=W) 
    master.after(self.time,master.destroy()) 

MessageShort(root,"Select date and decimal format",2000)#call from another part to the class to create the GUI message 

root = Tk() 
app = App(root) #main App 
root.mainloop() 

應用的一小部分有不同的菜單和Tkinter的類來顯示不同的工具 隨着當前的代碼,我關閉應用程序,我只是想關閉的消息,但沒有在App

+0

爲什麼這些其他解決方案不適合你?你試過的具體是什麼沒有奏效? –

+0

從'master.after(self.time,master.destroy())'中移除'()''看起來像'master.after(self.time,master.destroy)',否則你會直接調用destroy方法。 –

+0

謝謝@BryanOakley你是對的,而且非常接近 – gis20

回答

0

創建一個定時器,設定破壞的根源,因爲它的回調:

from threading import Timer 
import time 

def called_after_timer(): 
    if(root != None): 
    root.destroy() 

t = Timer(20 * 60, called_after_timeout) 
t.start() 

# do something else, such as 
time.sleep(1500) 
+0

root不能被破壞,否則應用程序被關閉 – gis20

+0

然後隱藏根窗口:call:'root.withdraw()'然後調用'newWin = Toplevel()'這將創建一個窗口不是根。因此即使在第二個窗口關閉後,root仍然會在主循環中運行。確保在某處調用root.destroy(),否則程序將不會退出。 –

0

最後我得到的東西,似乎工作

類MessageShort(tkSimpleDialog.Dialog):

def __init__(self, parent, text, time): 


     self.top=Toplevel.__init__(self, parent) 
     self.transient(parent) 
     self.parent = parent 
     self.text=text 
     self.time=time 
     body = Frame(self) 
     self.initial_focus = self.body(body) 
     body.pack(padx=10, pady=10) 
     if not self.initial_focus: 
      self.initial_focus = self 
     self.geometry("+%d+%d" % (parent.winfo_rootx()+200, 
           parent.winfo_rooty()+75)) 
     self.initial_focus.focus_set() 
     self.wait_window(self) 

    def body(self, master): 
     m=Message(master, text=self.text).grid(row=0,column=0,sticky=W) 
     master.after(self.time,self.destroy) 

MessageShort(root,"Select date and decimal format",2000)#call from another part to the class to create the GUI message 

root = Tk() 
app = App(root) #main App 
root.mainloop() 

在最後一行self.master.destroy破壞米而非容器本身。所以它必須打電話給self.destroy