添加右键退出
Showing
1 changed file
with
33 additions
and
9 deletions
| 1 | import pystray | 1 | import pystray |
| 2 | from PIL import Image, ImageDraw | 2 | from PIL import Image |
| 3 | import threading | 3 | import threading |
| 4 | import os | ||
| 5 | import sys | ||
| 4 | 6 | ||
| 5 | def create_image(width, height, color1, color2): | 7 | def load_icon(icon_path): |
| 6 | image = Image.new("RGB", (width, height), color1) | 8 | """加载图标文件""" |
| 7 | dc = ImageDraw.Draw(image) | 9 | try: |
| 8 | dc.rectangle((width // 2, 0, width, height // 2), fill=color2) | 10 | return Image.open(icon_path) |
| 9 | return image | 11 | except FileNotFoundError: |
| 12 | print(f"Icon file not found at {icon_path}") | ||
| 13 | return None | ||
| 14 | |||
| 15 | def on_exit(icon, item): | ||
| 16 | """退出程序的回调函数""" | ||
| 17 | icon.stop() # 停止托盘图标 | ||
| 18 | print("Exiting program...") | ||
| 19 | os._exit(0) # 强制退出程序 | ||
| 10 | 20 | ||
| 11 | def run_icon(icon_path): | 21 | def run_icon(icon_path): |
| 12 | image = Image.open(icon_path) # 加载自定义图标 | 22 | """运行系统托盘图标""" |
| 13 | icon = pystray.Icon("test_icon", image, "My System Tray Icon") | 23 | image = load_icon(icon_path) |
| 14 | icon.run() | 24 | if not image: |
| 25 | print("Failed to load icon. Exiting...") | ||
| 26 | return | ||
| 27 | |||
| 28 | # 创建系统托盘图标 | ||
| 29 | icon = pystray.Icon( | ||
| 30 | name="test_icon", | ||
| 31 | icon=image, | ||
| 32 | title="My System Tray Icon", | ||
| 33 | menu=pystray.Menu( | ||
| 34 | pystray.MenuItem("Exit", on_exit) # 添加右键菜单项 | ||
| 35 | ) | ||
| 36 | ) | ||
| 37 | icon.run() # 运行托盘图标 | ||
| 15 | 38 | ||
| 16 | def start_tray_icon(icon_path): | 39 | def start_tray_icon(icon_path): |
| 40 | """在新线程中启动系统托盘图标""" | ||
| 17 | threading.Thread(target=run_icon, args=(icon_path,), daemon=True).start() | 41 | threading.Thread(target=run_icon, args=(icon_path,), daemon=True).start() |
| ... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
-
Please register or sign in to post a comment