Dotan Raz Dotan Raz - 1 month ago 5
Python Question

Tkinter GUI stuck till end of the task when pressing a button

when i'm pressing the "start program" button it starts a 5 sec task and block the GUI.
as i understand i need to use Threading so each button will work independently from the GUI.
I'm stuck for almost a month already, can someone show me how can execute def start_Button(self): function using threading?

from tkinter import *
import time


class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()

def init_window(self):
self.var = IntVar()
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text="Exit", command=self.client_exit)
startButton = Button(self, text="Start Program", command=self.start_Button)

quitButton.grid(row=0,column=0)
startButton.grid(row=0, column=2)

def client_exit(self):
exit()

def start_Button(self):
print('Program is starting')
for i in range (5):
print(i)
time.sleep(1)


root = Tk()
root.geometry("200x50")
app = Window(root)
root.title("My Program")
root.mainloop()

Answer

There are a lot of important questions to ask before you jump into threading for the first time, but by and large the most important question is "how do I want to communicate between my threads?" In your minimal example you don't require any communication at all, however in your real code start_Button may be doing some Work and returning data back to the GUI. If that's the case, you have more work to do. Please clarify that as a comment if that's the case.

For the minimal example, it's actually quite easy.

class Window(tkinter.Frame):
    # the rest of your GUI class as written, but change...

    def start_Button(self):
        def f():
            # this is the actual function to run
            print('Program is starting')
            for i in range (5):
                print(i)
                time.sleep(1)
        t = threading.Thread(target=f)
        t.start()
Comments