简体   繁体   中英

Tkinter: 'after" function is still called after root has been destroyed

I am new to Python and I am trying to create a Restaurant simulation with Tkinter as my GUI (Since it is easy).

I have a Timer that uses function called Tick() (shown below:)

def Tick(self,time,type,resto,foodname,Database):
    if self.cookTimer.winfo_exists() is 1:
        .....
        else:
            if self.cookTimer.winfo_exists() is 1:
                self.timeLabel.configure(text="%d" %time)
                self.cookTimer.after(1000, lambda: self.Tick(time,type,resto,foodname,Database))
        self.cook.protocol("WM_DELETE_WINDOW", lambda: self.Callback(self.cook,resto,Database))

What I am trying to do is before exiting the program, it will ask the user Yes or No first. Now, in Tick() , the root is named self.cookTimer .

When the user already exited the self.cookTimer , self.timeLabel.configure is still running thus raising an error that configure needs the root.

Can anyone help me by telling me how to make the program NOT run configure if cookTimer is destroyed?

The Tkinter after method returns an identifier that can be used to cancel the scheduled call if it turns out you do not need it any more. A good example of this is setting up a timeout call. If your code completes within the timeout then you cancel the timeout. In your example, when you setup the after call, record the result and use that to cancel the call:

self.after_id = self.cookTimer.after(1000, lambda: ...)
....
self.after_cancel(self.after_id)

You might want to create a cleanup method and have the WM_PROTOCOL_DELETE and other termination calls all go there to cleanup and exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM