tkinter 与多线程

在Python的tkinter中,当执行长时间后台任务时,会导致用户界面UI无响应。由于线程限制,主线程之外的子线程不能直接更新UI。示例展示了如何在正确线程中调用tk.mainloop()以保持UI更新。
摘要由CSDN通过智能技术生成

长时间执行后台任务,UI会处于无响应状态。在子线程里更新UI状态,听说是不允许的。在哪个线程里调用了tk.mainloop(),就只能在哪个线程里更新UI。

下例演示了如何更新。

import Tkinter as tk
from ttk import *
import time
import Queue, threading

class MainWindow:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('Demo')

    def show(self):
        self.progress = tk.IntVar()
        self.progress_max = 100
        self.progressbar = Progressbar(self.root, mode='determinate', orient=tk.HORIZONTAL, variable=self.progress, maximum=self.progress_max)
        self.progressbar.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.progress.set(0)
        
        btn = tk.Button(self.root, text='start', command=self.start)
        btn.pack(fill=tk.BOTH, expand=True, padx=15, pady=5)
        self.btn = btn
        
        self.root.mainloop()

    def star
ThreadPoolExecutor是Python标准库concurrent.futures中的一个类,它提供了一种简单的方式来在多个线程中执行可调用对象。在Tkinter中使用ThreadPoolExecutor可以实现多线程操作,从而提高程序的效率。以下是一个使用ThreadPoolExecutor的Tkinter多线程示例: ```python import tkinter as tk from concurrent.futures import ThreadPoolExecutor class App(tk.Tk): def __init__(self): super().__init__() self.title("Tkinter多线程示例") self.geometry("300x200") self.label = tk.Label(self, text="点击按钮开始计算") self.label.pack(pady=20) self.button = tk.Button(self, text="开始", command=self.start_calculation) self.button.pack(pady=10) self.executor = ThreadPoolExecutor(max_workers=2) def start_calculation(self): self.button.config(state="disabled") self.label.config(text="正在计算...") self.executor.submit(self.calculation_complete) def calculation_complete(self): # 模拟计算 import time time.sleep(5) self.label.config(text="计算完成") self.button.config(state="normal") if __name__ == "__main__": app = App() app.mainloop() ``` 在这个示例中,我们创建了一个Tkinter应用程序,包含一个标签和一个按钮。当用户点击按钮时,我们使用ThreadPoolExecutor在后台启动一个新线程来模拟计算,并在计算完成后更新标签的文本。注意,在Tkinter中更新UI必须在主线程中进行,因此我们使用submit方法将计算任务提交给ThreadPoolExecutor,而不是直接在新线程中更新UI。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值