如何用Python案例实现任务栏提示?

wen python案例 5

本文目录导读:

如何用Python案例实现任务栏提示?

  1. 使用 Windows 原生通知(Toast通知)
  2. 带图标和进度条的高级通知
  3. 系统托盘图标通知
  4. 定时提醒功能
  5. 完整案例:文件监控通知
  6. 安装依赖
  7. 使用建议

我来为您介绍几种在Python中实现任务栏通知的方法:

使用 Windows 原生通知(Toast通知)

使用 win10toast

# 首先安装:pip install win10toast
from win10toast import ToastNotifier
def show_windows_toast():
    toaster = ToastNotifier()
    # 显示通知
    toaster.show_toast(
        "任务提醒",  # 标题
        "这是一个来自Python的任务栏通知!",  # 内容
        duration=5,  # 显示时长(秒)
        threaded=True  # 是否使用线程(避免阻塞)
    )
# 调用函数
show_windows_toast()

使用 plyer 库(跨平台)

# 安装:pip install plyer
from plyer import notification
def show_notification():
    notification.notify(
        title='任务提醒',
        message='这是一个跨平台的任务栏通知!',
        app_name='Python应用',
        timeout=5  # 显示时间
    )
show_notification()

带图标和进度条的高级通知

from win10toast import ToastNotifier
import time
from threading import Thread
class TaskNotifier:
    def __init__(self):
        self.toaster = ToastNotifier()
    def show_progress_notification(self, task_name, progress):
        """
        显示带进度信息的通知
        """
        if progress < 100:
            message = f"任务 '{task_name}' 进行中... {progress}%"
        else:
            message = f"任务 '{task_name}' 已完成! ✓"
        self.toaster.show_toast(
            "任务进度",
            message,
            duration=3,
            threaded=True
        )
    def simulate_long_task(self):
        """
        模拟长时间运行的任务
        """
        for i in range(0, 101, 20):
            self.show_progress_notification("数据处理", i)
            time.sleep(2)  # 模拟任务执行
# 使用示例
notifier = TaskNotifier()
notifier.simulate_long_task()

系统托盘图标通知

# 安装:pip install pystray Pillow
import pystray
from PIL import Image, ImageDraw
import threading
import time
def create_tray_icon():
    """
    创建系统托盘图标
    """
    # 创建一个简单的图标
    image = Image.new('RGB', (64, 64), 'blue')
    dc = ImageDraw.Draw(image)
    dc.rectangle((16, 16, 48, 48), fill='white')
    def on_clicked(icon, item):
        if str(item) == "显示消息":
            icon.notify("这是一条来自托盘的消息!")
        elif str(item) == "退出":
            icon.stop()
    # 创建托盘菜单
    menu = pystray.Menu(
        pystray.MenuItem("显示消息", on_clicked),
        pystray.MenuItem("退出", on_clicked)
    )
    # 创建并运行托盘图标
    icon = pystray.Icon("test", image, "Python托盘应用", menu)
    icon.run()
# 运行托盘图标(会在系统托盘中显示)
# create_tray_icon()  # 取消注释即可运行

定时提醒功能

import time
from plyer import notification
from threading import Timer
import datetime
class ReminderSystem:
    def __init__(self):
        self.reminders = []
    def add_reminder(self, message, delay_seconds):
        """
        添加定时提醒
        :param message: 提醒内容
        :param delay_seconds: 延迟秒数
        """
        reminder_time = datetime.datetime.now() + datetime.timedelta(seconds=delay_seconds)
        self.reminders.append({
            'message': message,
            'time': reminder_time,
            'delay': delay_seconds
        })
        # 设置定时器
        Timer(delay_seconds, self._show_reminder, args=[message]).start()
        print(f"提醒已设置:{message}(将在{delay_seconds}秒后提醒)")
    def _show_reminder(self, message):
        """显示提醒通知"""
        notification.notify(
            title='提醒!',
            message=message,
            app_name='Python提醒器',
            timeout=5
        )
    def list_reminders(self):
        """列出所有待处理的提醒"""
        now = datetime.datetime.now()
        for r in self.reminders:
            if r['time'] > now:
                remaining = (r['time'] - now).seconds
                print(f"待提醒:{r['message']}(剩余{remaining}秒)")
# 使用示例
reminder = ReminderSystem()
reminder.add_reminder("休息一下,喝杯水!", 10)  # 10秒后提醒
reminder.add_reminder("检查邮件", 20)  # 20秒后提醒
# 显示所有待处理提醒
reminder.list_reminders()

完整案例:文件监控通知

import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from plyer import notification
class FileMonitorNotifier(FileSystemEventHandler):
    def __init__(self, watch_directory):
        self.watch_directory = watch_directory
        self.observer = Observer()
    def on_created(self, event):
        """文件创建时触发"""
        if not event.is_directory:
            self.show_notification(
                "文件创建",
                f"新文件:{os.path.basename(event.src_path)}"
            )
    def on_modified(self, event):
        """文件修改时触发"""
        if not event.is_directory:
            self.show_notification(
                "文件修改",
                f"文件已修改:{os.path.basename(event.src_path)}"
            )
    def on_deleted(self, event):
        """文件删除时触发"""
        if not event.is_directory:
            self.show_notification(
                "文件删除",
                f"文件已被删除:{os.path.basename(event.src_path)}"
            )
    def show_notification(self, title, message):
        """显示通知"""
        notification.notify(
            title=title,
            message=message,
            app_name='文件监控器',
            timeout=3
        )
    def start_monitoring(self):
        """开始监控"""
        self.observer.schedule(self, self.watch_directory, recursive=False)
        self.observer.start()
        print(f"开始监控目录:{self.watch_directory}")
        print("按 Ctrl+C 停止监控")
        try:
            while self.observer.is_alive():
                time.sleep(1)
        except KeyboardInterrupt:
            self.observer.stop()
        self.observer.join()
# 使用示例
if __name__ == "__main__":
    # 监控当前目录
    monitor = FileMonitorNotifier(r"C:\Your\Target\Directory")  # 修改为你想要监控的目录
    monitor.start_monitoring()

安装依赖

根据你选择的方法,安装相应的库:

# Windows通知
pip install win10toast
# 跨平台通知
pip install plyer
# 系统托盘图标
pip install pystray Pillow
# 文件监控
pip install watchdog

使用建议

  1. Windows用户:推荐使用 win10toast,显示效果最好
  2. 跨平台需求:使用 plyer,支持Windows、macOS、Linux
  3. 长期运行的应用:结合系统托盘图标使用
  4. 定时任务:使用 Timerschedule

这些方法都可以实现美观的任务栏提示,你可以根据自己的需求选择最适合的方案。

抱歉,评论功能暂时关闭!