How to easily avoid Tkinter freezing?
Solution 1:
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.
Solution 2:
'Not responding' problem can be avoided using Multithreading in python using the thread module.
If you've defined any function, say combine()
due to which the Tkinter window is freezing, then make another function to start combine()
in background as shown below:
import threading def combine(): ... def start_combine_in_bg(): threading.Thread(target=combine).start()
Now instead of calling combine()
, you have to call start_combine_in_bg()
I did this and now my window is not freezing so I shared it here. Remember you can run only one thread at a time.
Have a look for reference: stackoverflow - avoid freezing of tkinter window using one line multithreading code