Python Win11toast 库实现通知按钮点击事件

使用 win11toast 库,你可以轻松地在 Python 中创建带有按钮的 Win11 通知弹窗,并通过回调函数处理按钮点击事件。

代码示例

from win11toast import ToastNotifier
import time

def on_button_clicked(button):
    if button == 'Approve':
        print('Approve button clicked')
    elif button == 'Dismiss':
        print('Dismiss button clicked')
    elif button == 'Other':
        print('Other button clicked')

toaster = ToastNotifier()
toaster.notification_click = on_button_clicked

toaster.show_toast('Hello', 'Click a button', buttons=['Approve', 'Dismiss', 'Other'])

# 保持通知显示,直到用户点击按钮
while toaster.notification_active():
    time.sleep(0.1)

代码解释

  1. 定义回调函数: on_button_clicked 函数作为回调函数,接收按钮文本作为参数,并根据按钮文本执行不同的操作。
  2. 创建 ToastNotifier 对象: toaster 对象用于创建通知。
  3. 设置回调函数: 将 on_button_clicked 函数赋值给 toaster.notification_click 属性,以便在按钮点击时调用该函数。
  4. 显示通知: 使用 toaster.show_toast 方法显示通知,并指定按钮文本。
  5. 保持通知显示: 使用循环和 toaster.notification_active() 属性确保通知持续显示,直到用户点击按钮。

注意

  • 为了接收按钮点击事件,你需要在 Windows 10 或更高版本上运行此代码,并且安装了 win11toast 库。
  • 你可以根据自己的需求修改回调函数 on_button_clicked 中的操作,实现不同的功能。
Python Win11toast 库实现通知按钮点击事件