1
votes

I've got a bit of a problem with the tkinter Toplevel widget. Whenever I try to destroy a toplevel window, it won't close, but instead it becomes inactive. Whenever I click the window, which should have been destroyed, I get a memoryaddress error. Does anybody know what I'm doing wrong?

Example code:

from tkinter import *
import _thread as thread
import time
root = Tk()
root.title('root')
login = Toplevel(root)
login.title('login')
thread.start_new_thread(root.mainloop,())
time.sleep(3)
login.destroy()
1
Don't use time.sleep() in asynchronous code. - Scorpion_God
Even without the destroy line, I get RuntimeError: Calling Tcl from different appartment. Seems that Tkinter doesn't play nice with threads in general. - Kevin
@Kevin: you are correct. - Bryan Oakley

1 Answers

1
votes

Tkinter is not thread-safe. All Tkinter calls should originate from a single thread. Use root.after to schedule a function call to happen after a delay.

from tkinter import *
root = Tk()
root.title('root')
login = Toplevel(root)
login.title('login')
root.after(3000, login.destroy)
root.mainloop()

Per the TkinterSummary:

All Tkinter access must be from the main thread (or, more precisely, the thread that called mainloop). Violating this is likely to cause nasty and mysterious symptoms such as freezes or core dumps.