tray_icon.py
1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import pystray
from PIL import Image
import threading
import os
import sys
def load_icon(icon_path):
"""加载图标文件"""
try:
return Image.open(icon_path)
except FileNotFoundError:
print(f"Icon file not found at {icon_path}")
return None
def on_exit(icon, item):
"""退出程序的回调函数"""
icon.stop() # 停止托盘图标
print("Exiting program...")
os._exit(0) # 强制退出程序
def run_icon(icon_path):
"""运行系统托盘图标"""
image = load_icon(icon_path)
if not image:
print("Failed to load icon. Exiting...")
return
# 创建系统托盘图标
icon = pystray.Icon(
name="test_icon",
icon=image,
title="My System Tray Icon",
menu=pystray.Menu(
pystray.MenuItem("Exit", on_exit) # 添加右键菜单项
)
)
icon.run() # 运行托盘图标
def start_tray_icon(icon_path):
"""在新线程中启动系统托盘图标"""
threading.Thread(target=run_icon, args=(icon_path,), daemon=True).start()