Reputation: 5
What is best way to get this work? Script hanging at showinfo:
from tkinter import *
from tkinter.messagebox import *
from threading import Timer
def timerDone():
showinfo('Alert','Alert')
window = Tk()
mainTimer = Timer(3, timerDone)
mainTimer.start()
window.mainloop()
I use Python 3. Is there is a way to get it work without Queue or additional imports?
I don't use "after" method because Timer can be stoped or changed - I have a lot of timers with dynamically changeable interval and this is very inconvenient.
Upvotes: 0
Views: 137
Reputation: 7842
As discussed here: python tkinter with threading causing crash
Tkinter is not thread safe; you cannot access Tkinter widgets from anywhere but the main thread.
You should remove the Timer
instantiation. Tk has its own tool for scheduling events called the after
method.
from tkinter import *
from tkinter.messagebox import *
def timerDone(window):
showinfo('Alert','Alert')
window.destroy()
window = Tk()
window.after(3000,lambda:timerDone(window))
window.mainloop()
This is the same script implemented using after
. I also added a window.destroy()
call to break the mainloop.
There are a couple of solutions to your problem. The simplest is to use the after_cancel
method to stop a callback from being executed. Its worth also noting that after
events are bound to a widget, so if the widget that owns the after
is destroyed, the callback will never be executed.
Upvotes: 2