Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically close window after a certain time

Tags:

python

tkinter

In a class, in a function I am creating a Tkinter Canvas. This function is being called by another class, I would like for the Tkinter window to pop up for 30 seconds and then close itself. I have it call

master.mainloop()
time.sleep(30)
master.destroy() 

But I get an error

"elf.tk.call('destroy', self._w) _tkinter.TclError: can't invoke "destroy" command: application has been destroyed"

So how can I have it close itself?

like image 894
EasilyBaffled Avatar asked Mar 09 '13 01:03

EasilyBaffled


2 Answers

Don't use time.sleep() with tkinter. Instead, call the function after on the widget you want to close.

Here it is the most simple example:

import tkinter as tk

w = tk.Tk()
w.after(30000, lambda: w.destroy()) # Destroy the widget after 30 seconds
w.mainloop()
like image 144
A. Rodas Avatar answered Oct 09 '22 11:10

A. Rodas


The problem here is that mainloop() does not return until the GUI has shut down.

So, 30 seconds after the GUI has shut down and destroyed itself, you try to destroy it. And obviously that fails.

But you can't just move the sleep and destroy calls inside the main loop, because if you sleep in the middle of the main loop, the GUI will freeze up.

So, you need some kind of timer that will not stop the main loop. tkinter includes the after method for exactly that purpose. This answer gives a detailed example of using it.

like image 4
abarnert Avatar answered Oct 09 '22 12:10

abarnert