好吧,我知道已经有一段时间了,但我试图弄清楚同样的事情,但我在任何地方都找不到一个好的、结论性的答案。我终于在 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:我尝试了一下,结果发现这可以让你点击任何地方,而不仅仅是按钮。不知道从那里去哪里,但值得一提。