pip install pystray Pillow
import sys
import logging
import time
import threading
from pystray import Icon, MenuItem, Menu
from PIL import Image, ImageDraw
# 设置日志
logging.basicConfig(filename='log.txt', level=logging.INFO)
def log_message(message):
logging.info(message)
print(message)
# 创建托盘图标
def create_image(width, height):
# 生成一个简单的图标
image = Image.new('RGB', (width, height), color=(255, 255, 255))
dc = ImageDraw.Draw(image)
dc.rectangle(
(width // 4, height // 4, width * 3 // 4, height * 3 // 4),
fill=(0, 128, 255)
)
return image
def show_log():
while True:
log_message(f"Current time: {time.strftime('%H:%M:%S')}")
time.sleep(5)
# 创建托盘菜单
def quit_action(icon, item):
icon.stop()
sys.exit()
# 主程序
if __name__ == '__main__':
# 启动日志线程
log_thread = threading.Thread(target=show_log, daemon=True)
log_thread.start()
# 创建托盘图标
icon = Icon("test_icon", create_image(64, 64), "Logging Tray", menu=Menu(
MenuItem("Quit", quit_action)
))
icon.run()