问题描述
我正在尝试使winRT发送通知。 我尝试这样做是为了发出通知:
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
#create notifier
nManager = notifications.Toastnotificationmanager
notifier = nManager.create_toast_notifier();
#define your notification as string
tString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Sample toast</text>
<text>Sample content</text>
</binding>
</visual>
</toast>
"""
#convert notification to an XmlDocument
xDoc = dom.XmlDocument()
xDoc.load_xml(tString)
#display notification
notifier.show(notifications.ToastNotification(xDoc))
但是,当我尝试运行它时,它将返回此错误。
notifier = notifications.Toastnotificationmanager.create_toast_notifier()
RuntimeError: Element not found.
我的系统满足winrt的要求
Windows 10,October 2018 Update or later.
Python for Windows,version 3.7 or later
pip,version 19 or later
如何解决此错误?我不能使用其他模块,因为winrt是(我知道的)唯一一个可以在通知上创建ui元素(如按钮)的模块。
解决方法
我刚刚解决了关于消除错误但未显示通知的相同问题。
此 Microsoft doc 建议“重要提示,每次调用 CreateToastNotifier 时,您都必须在开始屏幕上包含应用快捷方式的 AppUserModelID。如果不这样做,将不会显示您的 Toast。”
然后我按照我找到的说明 here 找到 AppUserModelID,结果证明它是我的 Python 可执行文件的完整路径。
例如:
notifier = nManager.create_toast_notifier("C:\\...\\Programs\\Python\\Python38\\python.exe")
,
发生异常是因为您需要在applicationID
中提供create_toast_notifier()
例如create_toast_notifier("MyApplicationId")
。
这也描述了here,但使用c#。
,此方法适用于 Python 3.9.1
和 pip 21.0.1
打开 PowerShell 输入以下命令 get-StartApps
它返回 Name
和 AppID
-
请参阅 imgur 上的表格或图片以供参考。
Name AppID ---- ----- Calculator Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
-
这很方便
get-StartApps | Where-Object {$_.Name -like '*Application Name*'}
get-StartApps | Where-Object {$_.Name -like '*Python*'}
复制/粘贴AppID
到create_toast_notifier("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App")
示例:
#create notifier
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App");