Freezing/Hanging Tkinter Gui in Waiting for the Thread to Complete

How to easily avoid Tkinter freezing?

Tkinter is in a mainloop. Which basically means it's constantly refreshing the window, waiting for buttons to be clicked, words to be typed, running callbacks, etc. When you run some code on the same thread that mainloop is on, then nothing else is going to perform on the mainloop until that section of code is done. A very simple workaround is spawning a long running process onto a separate thread. This will still be able to communicate with Tkinter and update it's GUI (for the most part).

Here's a simple example that doesn't drastically modify your psuedo code:

import threading

class Gui:
[...]#costructor and other stuff

def refresh(self):
self.root.update()
self.root.after(1000,self.refresh)

def start(self):
self.refresh()
threading.Thread(target=doingALotOfStuff).start()

#outside
GUI = Gui(Tk())
GUI.mainloop()

This answer goes into some detail on mainloop and how it blocks your code.

Here's another approach that goes over starting the GUI on it's own thread and then running different code after.

Call thread with loop out of gui without freezing gui

I could not figure out the solution I thought would work but I found this answer which I could adapt to my project and it now works as I wished.



Related Topics



Leave a reply



Submit