Tkinter objects being garbage collected from the wrong thread Tkinter objects being garbage collected from the wrong thread tkinter tkinter

Tkinter objects being garbage collected from the wrong thread


I had exactly the same problem

It was a nightmare to find the cause of the issue. I exaustivelly verified that no tkinter object was being called from any thread. I made a mechanism based in queues to handle tkinter objects in threads.There are many examples on the web on how to do that, or... search for a module 'mttkinter', a thread safe wrapper for Tkinter)

In a effort to force garbage collection, I used the "gc" method in the exit function of every TopLevel window of my App.

#garbage collectorimport gc...gc.collect()

but for some reason, closing a toplevel window continued to reproduce the problem. Anyway... it was precisely using some prints in the aforementioned "mttkinter" module that I detected that, in spite the widgets are being created in the main thread, they could be garbage collected when garbage collector is triggered inside another thread. It looks like that the garbage collector gathers all the garbage without any distinction of its provenience (mainthread or other threads?). Someone please correct me if I'm wrong.

My solution was to call the garbage collector explicitly using the queue as well.

PutInQueue(gc.collect)

Where "PutInQueue" belongs to a module created by me to handle tkinter object and other kind of objects with thread safety.

Hope this report can be of great usefullness to someone or, it it is the case, to expose any eventual bug in garbage collector.


Tkinter is not thread safe. Calling Tkinter objects in a thread may cause things such as "The del method on Widget verifies that the Widget instance is being deleted from the other thread."

You can use locking and queues to make it done properly.

Check this example:Tkinter: How to use threads to preventing main event loop from "freezing"

and this example (there are many many other examples you can find):Mutli-threading python with Tkinter

Hope this will put you in the right direction.