【问题标题】:When i try to make a notification with winrt, it makes an error当我尝试使用 winrt 发出通知时,它会出错
【发布时间】:2020-10-06 18:16:16
【问题描述】:

我正在尝试让 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 元素。

【问题讨论】:

    标签: python windows notifications windows-runtime


    【解决方案1】:

    我刚刚解决了关于消除错误但未显示通知的相同问题。

    Microsoft doc 建议“重要您必须在每次调用 CreateToastNotifier 时在开始屏幕上包含应用快捷方式的 AppUserModelID。如果您不这样做,则不会显示您的 toast。”

    然后我按照我找到的说明here 找到了 AppUserModelID,结果证明它是我的 Python 可执行文件的完整路径。

    例如:

    notifier = nManager.create_toast_notifier("C:\\...\\Programs\\Python\\Python38\\python.exe")
    

    【讨论】:

    【解决方案2】:

    发生异常是因为您需要在create_toast_notifier() 中提供applicationID
    例如create_toast_notifier("MyApplicationId")

    这也描述了here,但在 c# 中。

    【讨论】:

    • 它摆脱了错误,但是当我运行程序时,没有出现任何通知。
    • 我一直在努力寻找解决方案,但遗憾的是我找不到任何东西。
    【解决方案3】:

    此方法适用于 Python 3.9.1pip 21.0.1


    打开 PowerShell 输入以下命令 get-StartApps 它返回 NameAppID

    • 请参阅imgur 上的表格或图片以供参考。

      Name            AppID                                          
      ----            -----
      Calculator      Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
      
    • 这很方便

      • get-StartApps | Where-Object {$_.Name -like '*Application Name*'}
      • get-StartApps | Where-Object {$_.Name -like '*Python*'}

    复制/粘贴 AppIDcreate_toast_notifier("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App")

    例子:

    #create notifier
    nManager = notifications.ToastNotificationManager
    notifier = nManager.create_toast_notifier("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App");
    

    【讨论】:

      猜你喜欢
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2018-07-29
      • 2019-09-23
      • 2021-09-06
      • 1970-01-01
      • 2020-06-17
      相关资源
      最近更新 更多