Python Win11toast 库实现通知按钮点击事件
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)
代码解释
- 定义回调函数:
on_button_clicked函数作为回调函数,接收按钮文本作为参数,并根据按钮文本执行不同的操作。 - 创建 ToastNotifier 对象:
toaster对象用于创建通知。 - 设置回调函数: 将
on_button_clicked函数赋值给toaster.notification_click属性,以便在按钮点击时调用该函数。 - 显示通知: 使用
toaster.show_toast方法显示通知,并指定按钮文本。 - 保持通知显示: 使用循环和
toaster.notification_active()属性确保通知持续显示,直到用户点击按钮。
注意
- 为了接收按钮点击事件,你需要在 Windows 10 或更高版本上运行此代码,并且安装了
win11toast库。 - 你可以根据自己的需求修改回调函数
on_button_clicked中的操作,实现不同的功能。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qod8 著作权归作者所有。请勿转载和采集!