tk借助Thread包实现多线程实例

本文介绍如何使用Tcl语言创建多线程执行特定任务,包括文件搜索和定时消息输出等示例。通过具体代码展示了如何利用thread包来提高程序执行效率。

对于有需求进行多线程操作,或者有界面相关操作的运算以及后台处理情况,可以通过多现场操作。

一下例子:Creating a separate thread to perform a lengthy operation

package require Thread

# Create a separate thread to search the current directory
# and all its subdirectories, recursively, for all files
# ending in the extension ".tcl". Store the results in the
# file "files.txt".

thread::create {
   # Load the Tcllib fileutil package to use its
   # findByPattern procedure.

   package require fileutil

   set files [fileutil::findByPattern [pwd] *.tcl]

   set fid [open files.txt w]
   puts $fid [join $files \n]
   close $fid
}

# The main thread can perform other tasks in parallel...

对于需要在{}中体现变量数据的情况,可以通过如下结构实现:

thread::create [list exec app.exe]

以下实例:在应用中创建多线程Creating several threads in an application

package require Thread

puts "*** I'm thread [thread::id]"

# Create 3 threads

for {set thread 1} {$thread <= 3} {incr thread} {
   set id [thread::create {

      # Print a hello message 3 times, waiting
      # a random amount of time between messages

      for {set i 1} {$i <= 3} {incr i} {
         after [expr { int(500*rand()) }]
         puts "Thread [thread::id] says hello"
      }

   }] ;# thread::create

   puts "*** Started thread $id"
} ;# for

puts "*** Existing threads: [thread::names]"

# Wait until all other threads are finished

while {[llength [thread::names]] > 1} {
   after 500
}

puts "*** That's all, folks!"








### 创建带有任务栏托盘图标的多线程Tkinter应用程序 在Python中使用`tkinter`创建窗口的同时,在任务栏显示托盘图标可以通过引入多线程技术来实现。这不仅能够保持GUI响应灵敏,还能有效管理后台任务。 #### 导入必要的库 首先需要导入所需的库,括用于构建图形用户界面的`tkinter`以及支持多线程操作的`threading`模块: ```python import tkinter as tk from tkinter import messagebox import threading import os try: # For Windows systems from win10toast_click import ToastNotifier except ImportError: pass # Non-Windows platforms will skip this part ``` #### 定义主窗口类 定义一个继承自`tk.Tk`的类作为主要的应用程序框架,并在此基础上添加其他组件或功能特性。 ```python class App(tk.Tk): def __init__(self): super().__init__() # 设置窗口属性 self.title("Main Window with Tray Icon Example") self.geometry('300x200') # 初始化托盘图标逻辑... ``` #### 实现任务栏托盘图标的功能 对于Windows平台来说,可以借助第三方如`win10toast-click`来简化通知和托盘图标的创建过程;而对于Linux或其他操作系统,则可能需要采用不同的策略。这里仅展示基于Windows环境下的解决方案[^5]。 ```python def create_tray_icon(): """Create a tray icon that can show notifications and handle clicks.""" toast = ToastNotifier() def on_click(icon_path=None): if not icon_path or not os.path.exists(icon_path): icon_path = "path_to_your_default_icon.ico" response = toast.show_toast( title="Application Name", msg="Click here to restore the window.", duration=10, threaded=True, callback_on_click=lambda: app.deiconify() ) return response thread = threading.Thread(target=on_click) thread.start() ``` 此函数负责创建一个可以在点击时恢复隐藏窗口的任务栏托盘图标,并发送桌面通知给用户。注意这里的回调机制允许我们在用户交互之后执行特定的动作,例如使最小化的窗口恢复正常可见状态。 #### 启动多线程处理 为了让上述两部分工作协同起来,应该在一个单独的工作线程中调用`create_tray_icon()`方法,这样就不会阻塞主线程上的UI更新循环了。 ```python if __name__ == "__main__": app = App() # 开启新线程用于创建托盘图标 threading.Thread(target=create_tray_icon).start() try: app.mainloop() except KeyboardInterrupt: exit(0) ``` 这段代码片段展示了如何初始化应用程序实例并将托盘图标放置于辅助线程之中运行,确保两者互不影响地各自运作着。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值