使用Python winrt模块实现带操作的Windows toast通知及按钮点击检测
问题解答
一、按钮点击事件检测实现
首先需要修正你现有代码的拼写错误:activationType属性你写的是backround,正确拼写为background,该错误会导致按钮行为异常。
实现点击检测的核心逻辑是给ToastNotification实例绑定Activated事件回调,用户点击按钮或者通知本体时,系统会触发该回调,同时把你定义的arguments参数透传给回调函数,你可以根据参数值执行不同的业务逻辑。
修正后的可运行代码如下:
import winrt.windows.ui.notifications as notifications import winrt.windows.data.xml.dom as dom import time # 测试可继续使用PowerShell的AUMID,生产环境建议替换为自定义的应用ID app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe' # 初始化通知管理器 nManager = notifications.ToastNotificationManager notifier = nManager.create_toast_notifier(app) # 修正拼写错误后的通知XML定义 tString = """ <toast> <visual> <binding template='ToastGeneric'> <text>New notifications</text> <text>Text</text> <text>Second text</text> </binding> </visual> <actions> <action content="test1" arguments="test1" activationType="background"/> <action content="test2" arguments="test2" activationType="background"/> </actions> </toast> """ # 加载通知XML xDoc = dom.XmlDocument() xDoc.load_xml(tString) # 生成通知实例 toast = notifications.ToastNotification(xDoc) # 定义点击事件回调 def on_activated(sender, args): # args.argument 就是你在按钮中定义的arguments值 print(f"收到操作,参数为:{args.argument}") if args.argument == "test1": print("执行test1对应的操作逻辑") elif args.argument == "test2": print("执行test2对应的操作逻辑") # 绑定激活事件 toast.add_activated(on_activated) # 弹出通知 notifier.show(toast) # 保持脚本运行才能接收事件,可根据需求调整等待时长 print("等待通知操作,30秒后自动退出...") time.sleep(30)
注意事项
- 脚本必须在通知有效期内保持运行才能收到点击回调,如果需要脚本退出后仍能响应操作,需要额外注册Windows后台任务,实现复杂度较高。
arguments参数支持自定义任意字符串,你可以传入JSON格式的结构化参数,用来区分不同通知、不同操作类型。
二、Toast XML参数说明
arguments是自定义透传参数,系统不会解析它的内容,只会在用户点击对应操作项时,把字符串原样传递给激活事件处理函数,你可以根据业务需求自由定义内容。
微软官方有完整的Toast内容XML架构定义,涵盖所有标签和属性的用法,包括visual、actions、audio等所有节点的配置规则,你可以自行查找对应文档。
内容的提问来源于stack exchange,提问作者metalex
相关产品推荐
相关产品推荐

