一段时间后关闭tkinter GUI

时间:2016-07-30 21:58:13

标签: python tkinter destroy

我想创建一个显示消息的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()

App有不同的菜单和Tkinter类来显示不同的工具 使用当前代码,我关闭应用程序,我只想关闭消息而不是应用程序

2 个答案:

答案 0 :(得分:0)

创建一个计时器并设置销毁root作为回调:

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)

答案 1 :(得分:0)

最后我得到了似乎有用的东西

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,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会破坏m但不会破坏容器本身。所以它必须调用self.destroy