2014-10-20 136 views
0

我需要一个应用程序,基本上运行一个进度栏几秒钟,然后关闭自己。我使用this as an example,同时首先适用于Python 3.4,然后用于我自己的应用程序。但是,由于我构建代码的方式,它将首先运行线程,它的任务是完成,然后才显示程序。这对我来说是非常有问题的,而且在使用类时我没有看到它。Tkinter冻结与多线程

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() 

回答

2

好吧,你的示例代码,你可以删除调用t1.join()得到你想要的行为。这样,在启动后台线程后,您将能够立即启动Tk事件循环,这意味着您的GUI实际上可以在线程在后台运行时启动。使用t1.join()调用会阻止root.mainloop()执行,直到线程完成,这意味着在线程完成之前您的GUI也不会显示。