使用 python winrt 模块进行 Windows Toast 通知和操作

2024-01-16

我已经尝试让它工作很长时间了,但我总是陷入检测按钮按下的困境。我做了一个 toast 通知,如下所示:

这是我的代码:

import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom

app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'

#create notifier
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier(app)

#define your notification as string
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="backround"/>
       <action
           content="test2"
           arguments="test2"
           activationType="backround"/>
   </actions>

</toast>
"""
print(type(notifier.update))

#convert notification to an XmlDocument
xDoc = dom.XmlDocument()
xDoc.load_xml(tString)

#display notification
notifier.show(notifications.ToastNotification(xDoc))

我不知道如何检测按钮按下情况 我唯一想到的是,如果我将按钮的参数更改为如下链接:

arguments="https://google.com"

然后它会打开它 我有什么办法可以实现这个吗?或者是否有这些 Toast 通知使用的 XML 格式的文档。这解释了论证是如何运作的?


好吧,我知道已经有一段时间了,但我试图弄清楚同样的事情,但我在任何地方都找不到一个好的、结论性的答案。我终于在 Python 3.9 中找到了可以与 WinRT 一起使用的东西,所以我希望人们可以在某个地方找到答案!

首先,我不太熟悉“arguments”属性的工作原理,但至少对于简单的用例来说它似乎并不重要。我所知道的大部分内容都来自于Windows Toast 文档 https://learn.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotification?view=winrt-22000。以下是一些代码,当您单击该按钮时,它们应该生成通知并打开您的文档文件夹。我从以下答案中获得了先机这个线程 https://stackoverflow.com/questions/64230231/how-can-i-can-send-windows-10-notifications-with-python-that-has-a-button-on-the但它缺少一些非常重要的步骤。

import os,sys,time
import subprocess
import threading
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom

# this is not called on the main thread!
def handle_activated(sender, _):
    path = os.path.expanduser("~\Documents")
    subprocess.Popen('explorer "{}"'.format(path))

def test_notification():
    #define your notification as
    tString = """
    <toast duration="short">

        <visual>
            <binding template='ToastGeneric'>
                <text>New notifications</text>
                <text>Text</text>
                <text>Second text</text>
            </binding>
        </visual>

        <actions>
            <action
                content="Test Button!"
                arguments=""
                activationType="foreground"/>
        </actions>

    </toast>
    """

    #convert notification to an XmlDocument
    xDoc = dom.XmlDocument()
    xDoc.load_xml(tString)
    notification = notifications.ToastNotification(xDoc)

    # add the activation token.
    notification.add_activated(handle_activated)

    #create notifier
    nManager = notifications.ToastNotificationManager
    #link it to your Python executable (or whatever you want I guess?)
    notifier = nManager.create_toast_notifier(sys.executable)

    #display notification
    notifier.show(notification)
    duration = 7 # "short" duration for Toast notifications

    # We have to wait for the results from the notification
    # If we don't, the program will just continue and maybe even end before a button is clicked
    thread = threading.Thread(target=lambda: time.sleep(duration))
    thread.start()
    print("We can still do things while the notification is displayed")

if __name__=="__main__":
    test_notification()

这里要注意的关键是你需要找到一种方法来等待通知的响应,因为通知是由与生成通知的程序不同的线程处理的。这就是为什么你的“www.google.com”示例有效,而其他示例则无效,因为它与 Python 程序没有任何关系。

可能有一个更优雅的解决方案,但一种快速简单的方法是创建一个 Python 线程并在那里等待一段时间。这样,如果您需要做其他事情,它就不会干扰您程序的其余部分。如果您希望程序等待响应,请使用time.sleep(duration)没有所有线程代码来暂停整个程序。

我不确定它到底是如何工作的,但似乎 add_activated 函数只是将回调处理程序分配给 XML 中的下一个可用块。所以如果你想添加另一个按钮,my guess是您可以按照与列出按钮相同的顺序使用另一个回调处理程序执行 add_activated 。

Edit:我尝试了一下,结果发现这可以让你点击任何地方,而不仅仅是按钮。不知道从那里去哪里,但值得一提。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python winrt 模块进行 Windows Toast 通知和操作 的相关文章

  • python的_random是什么?

    如果你打开random py看看它是如何工作的 它的类Random子类 random Random import random class Random random Random Random number generator base
  • 对 Python DataFrame 进行子集化

    我正在从 R 过渡到 Python 我刚刚开始使用 Pandas 我有一个可以很好地子集化的 R 代码 k1 lt subset data Product p id Month lt mn Year yr select c Time Pro
  • Python中使用cv2获取当前视频播放位置

    我正在尝试使用 CV2 和 Python 从播放视频中获取当前播放时间位置 如果可能 以毫秒为单位 目前我正在使用此示例代码来播放视频文件 import cv2 import numpy as np file name 2 mp4 wind
  • Python 可以使用单独的媒体播放器打开 mp3 文件吗? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 是否可以开一个mp3Python 中的文件 可以使用Popen 我并不是要在程序中运行它 我的意思是作为媒体播放器中的一个单独窗口或其
  • 当我使用 SetWindowsHookEx WH_KEYBOARD_LL 交换按键时,为什么我的程序会陷入过多键盘输入事件的循环?

    I am trying to write a program for Windows system that swaps the A and B keys i e when I press the A key B gets typed an
  • 肥皂服务的良好框架是什么?

    我正在寻找一个用于肥皂的好框架service 我更喜欢使用Pythonic框架 但是在查看了soaplib rpclib 太不稳定 SOAPy 不适用于2 7 和ZSI 太 令人困惑 之后 我不确定这是否可能 我对使用另一种语言感到满意 尽
  • 如何使用泛型类型的构造函数

    如何使用 python 泛型类型的构造函数 T typing TypeVar T class MyClass typing Generic T def init self initialValue typing Iterable self
  • Python变量赋值问题

    a b 0 1 while b lt 50 print b a b b a b 输出 1 2 4 8 16 32 wheras a b 0 1 while b lt 50 print b a b b a b 输出 正确的斐波那契数列 1 1
  • Python 函数可能会引发哪些异常? [复制]

    这个问题在这里已经有答案了 Python 中有什么方法可以确定 内置 函数可能引发哪些异常 例如 文档 http docs python org lib built in funcs html http docs python org li
  • 修改正在运行的可执行文件的资源内容

    All 我将应用程序设置存储在资源中 当我的程序首次加载时 我使用 WinAPI 读取指定的资源 然后我解析检索到的字节数据 这对我来说完美无缺 现在假设用户更改了我的应用程序中的设置 他 她检查复选框控件 我想将更新的设置保存到我的资源中
  • 尝试修复我的功能

    我正在开发一个函数 我必须返回一个元组 其中第一个参数是最大数字的 str 第二个参数是 int 列表 这是示例以及我为该函数编写的内容 投票 G G N G C G 1 3 0 1 您必须将最大值的位置映射到正确的一方 parties N
  • 在Python中引用不带换行符的长字符串

    我正在尝试在 Python 中编写一个长字符串 该字符串显示为 OptParser 选项的帮助项 在我的源代码 py 文件中 我想放置换行符 以便我的代码不会花费新行 但是 我不希望这些换行符影响代码运行时该字符串的显示方式 例如 我想写
  • Tornado websocket handler , self.close() 正在关闭连接而不触发 on_close() 方法

    我是 python stackoverflow tornado 的新手 所以请耐心等待 纠正我 我正在使用龙卷风开发实时应用程序 当我在 Websocket 处理程序类中调用 self close 时 on close 方法不会启动 这次我
  • Control.FindForm 和 ContainerControl.ParentForm 有什么区别

    我想知道两者之间是否有任何功能 或其他 差异Control FindForm and ContainerControl ParentForm 我一直在使用 ParentForm创建我自己的用户控件时 但有什么原因吗 FindForm会是一个
  • 检测图像是否损坏或损坏

    我需要以编程方式检查用户在我的应用程序上选择作为壁纸的图像是否已损坏或损坏 基本上我为用户提供了选择自己的图像作为壁纸的选项 现在 当图像加载时 我只想检查它是否已损坏 如果您正在寻找 PHP 解决方案而不是 javascript 解决方案
  • python 函数返回 javascript date.getTime()

    我正在尝试创建一个简单的 python 函数 它将返回与 javascript 相同的值new Date getTime 方法 如所写here http www w3schools com js js dates asp javascrip
  • 使用 Pandas 和 Group By 绘制堆叠直方图

    我正在使用如下所示的数据集 Gender Height Width Male 23 4 4 4 Female 45 4 4 5 我想可视化高度和宽度的堆叠直方图 我希望每个图有两个堆叠的直方图 每个性别一个 这是文档中的堆叠直方图 如果存在
  • python pandas如何在多个条件下过滤字符串

    我有以下数据框 import pandas as pd data 5Star FiveStar five star fiv estar data pd DataFrame data columns columnName 当我尝试用一 种条件
  • Pandas 替换特定列上的值

    我知道这两个类似的问题 熊猫替换值 https stackoverflow com questions 27117773 pandas replace values Pandas 替换数据框中的列值 https stackoverflow
  • PyQt QFileDialog exec_ 很慢

    我正在使用自定义QFileDialog因为我想选择多个目录 但是exec 功能非常慢 我不明白为什么 我正在使用最新版本的 PyQt 代码片段 from PyQt4 import QtGui QtCore QtNetwork uic cla

随机推荐