Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily avoid Tkinter freezing?

I developed a simple Python application doing some stuff, then I decided to add a simple GUI using Tkinter.

The problem is that, while the main function is doing its stuff, the window freezes.

I know it's a common problem and I've already read that I should use multithreads (very complicated, because the function updates the GUI too) or divide my code in different function, each one working for a little time. Anyway I don't want to change my code for such a stupid application.

My question is: is it possible there's no easy way to update my Tkinter window every second? I just want to apply the KISS rule!

I'll give you a pseudo code example below that I tried but didn't work:

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

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

        def start(self):
            self.refresh()
            doingALotOfStuff()

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

It simply will execute refresh only once, and I cannot understand why.

Thanks a lot for your help.

like image 923
decadenza Avatar asked Feb 23 '17 17:02

decadenza


1 Answers

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.

like image 114
double_j Avatar answered Oct 04 '22 13:10

double_j