Mateusz J
Mateusz J

Reputation: 45

Tkinter freezing with multi threading

I need an application that basically runs a progress bar for a few seconds, and then closes itself down. I used this as an example whilst adapting it first for Python 3.4 and then for my own application. However, due to the way I've structured my code, it will first run the thread and it's tasks to it's completion and only then display the programme. This is very problematic for me, and I don't see a way around it when using classes.

from tkinter import ttk as ttk
from tkinter import *
import threading
import time



class App:
    def afterLoading(self):
        print('Loading finished')

    def process(self,master):
        time.sleep(2)
        print('Thread Done')
        self.afterLoading()

    def __init__(self, master):
        print()
        master.geometry("1270x800")
        master.resizable(0,0)


        t1 = threading.Thread(target=self.process, args=(master,))
        t1.start()
        self.loadingFrame(master)
        t1.join()

    def loadingFrame(self, master):

        frame = Frame(master, width=500, height=300)
        frame.pack(side=BOTTOM, pady=50)

        self.bar = ttk.Progressbar(frame, orient='horizontal', mode = 'indeterminate')
        self.bar.pack(fill=BOTH)
        self.bar.start(50)
        self.loadingLabel = Label(frame, text="Please wait whilst the programme initializes.")
        self.loadingLabel.pack()





root = Tk()
b = App(root)
root.mainloop()

Upvotes: 0

Views: 777

Answers (1)

dano
dano

Reputation: 94871

Well, with your example code, you can just remove the call to t1.join() to get the behavior you want. That way, you'll be able to start the Tk event loop immediately after starting the background thread, which means your GUI can actually start up while the thread runs in the background. Using the t1.join() call prevents root.mainloop() from executing until the thread is complete, which means your GUI won't display until the thread is complete, either.

Upvotes: 3

Related Questions