28fd1953 by huangyf2

添加右键退出

1 parent 92bcaa4a
import pystray
from PIL import Image, ImageDraw
from PIL import Image
import threading
import os
import sys
def create_image(width, height, color1, color2):
image = Image.new("RGB", (width, height), color1)
dc = ImageDraw.Draw(image)
dc.rectangle((width // 2, 0, width, height // 2), fill=color2)
return image
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 = Image.open(icon_path) # 加载自定义图标
icon = pystray.Icon("test_icon", image, "My System Tray Icon")
icon.run()
"""运行系统托盘图标"""
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()
\ No newline at end of file
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!