tkinter多线程的应用(临时版).py

from tkinter import *
import datetime
import threading


def do_word():      # 这里没特别的需求不需要动
    global a
    if a:
        t = threading.Thread(target=task)
        t.setDaemon(True)
        t.start()
    root.after(100,do_word)

def task():
    # 这里放超耗时间的东西,如请求服务器,读或写文件等。
    # 注意的是一般读写分离,
    # 读文件一条线程,写文件一条线程或者使用队列就不用分两条线程操作了。
    dd = datetime.datetime.now()
    label['text'] = dd


def one_word():
    print('开始')
    global a
    a = 1

def quit_word():
    print('暂停')
    global a
    a =0

# 说是多线程这里只用了一个线程,仅供参考。
# 作者:hhaoao

a = 0       # 控制线程的开关
root = Tk()
button = Button(root,text='开始',command=one_word)
quit_button = Button(root,text='暂停',command=quit_word)
label = Label(root,text='redy...')

button.grid()
quit_button.grid()
label.grid()
do_word()
root.mainloop()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值