from tkinter import ttk, Tk, StringVar
import time
import threading
class Window(Tk):
def __init__(self, **kw):
super().__init__(**kw)
self.download_thread = None
self.download_button = ttk.Button(self, text="开始下载", command=self.start_download_thread)
self.result_label = ttk.Label(self, text="")
self.text_var = StringVar(self)
self.entry = ttk.Entry(self, textvariable=self.text_var)
self.label = ttk.Label(self, textvariable=self.text_var)
self.text_var.trace_add("write", self.update_text())
self.download_button.grid(row=0, column=0)
self.result_label.grid(row=1, column=0)
self.entry.grid(row=0, column=1)
self.label.grid(row=1, column=1)
def start_download_thread(self):
if self.download_thread is None or not self.download_thread.is_alive():
self.download_thread = threading.Thread(target=self.download, daemon=True)
self.download_thread.start()
def download(self):
# 模拟下载任务,这里可以替换为实际的下载操作
for i in range(1, 6):
self.result_label.config(text=f"下载中... ({i}/5)")
self.update() # 更新主界面以显示下载进度
time.sleep(2) # 模拟下载延迟
self.result_label.config(text="下载完成")
def update_text(self, *args):
def wrap(*args):
self.text_var.set(self.entry.get())
return wrap
root = Window()
root.title("多线程示例")
root.mainloop()