Python 多线程Tkinter冻结
我需要一个应用程序,基本上运行一个进度条几秒钟,然后关闭自己。我先将其用于Python 3.4,然后用于我自己的应用程序。然而,由于我构建代码的方式,它将首先运行线程及其任务,直到完成,然后才显示程序。这对我来说是一个很大的问题,在使用类时,我看不到解决这个问题的方法Python 多线程Tkinter冻结,python,multithreading,tkinter,Python,Multithreading,Tkinter,我需要一个应用程序,基本上运行一个进度条几秒钟,然后关闭自己。我先将其用于Python 3.4,然后用于我自己的应用程序。然而,由于我构建代码的方式,它将首先运行线程及其任务,直到完成,然后才显示程序。这对我来说是一个很大的问题,在使用类时,我看不到解决这个问题的方法 from tkinter import ttk as ttk from tkinter import * import threading import time class App: def afterLoadin
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()
好的,使用示例代码,您只需删除对
t1.join()
的调用即可获得所需的行为。这样,您就可以在启动后台线程后立即启动Tk
事件循环,这意味着您的GUI实际上可以在线程在后台运行时启动。使用t1.join()
调用可以防止root.mainloop()
在线程完成之前执行,这意味着在线程完成之前也不会显示GUI