win10toast show_toast显示永久通知,当用户点击时关闭通知
时间: 2023-08-16 19:05:46 浏览: 63
可以通过添加一个回调函数来实现这个功能。当用户点击通知时,回调函数会被触发并关闭通知。
以下是一个示例代码:
```python
from win10toast import ToastNotifier
def on_notification_clicked():
# 通知被点击时执行的代码
print('Notification clicked')
toaster.hide_toast()
toaster = ToastNotifier()
toaster.show_toast(
'标题', '内容', duration=0, threaded=True, callback_on_click=on_notification_clicked)
# 让程序保持运行,以便等待通知被点击
import time
while toaster.notification_active():
time.sleep(0.1)
```
在这个例子中,我们通过将duration设为0来使通知永久显示。我们还设置了一些其他的参数,如threaded=True以确保通知是在新的线程中显示,以免阻塞主线程。最重要的是,我们添加了一个回调函数callback_on_click,它在用户点击通知时被触发。在这个回调函数中,我们关闭了通知。
相关问题
win10toast show_toast 参数
win10toast 是一个 Python 库,用于在 Windows 10 操作系统上显示桌面通知。show_toast() 函数是其主要功能之一,用于显示通知。
该函数的参数如下:
- title:通知的标题。
- msg:通知的内容。
- duration:通知的显示时间(毫秒)。默认值为 5 秒。
- icon_path:通知图标的路径。如果未指定,则使用默认图标。
- threaded:如果设置为 True,则在新线程中显示通知。默认值为 False。
- callback_on_click:当用户单击通知时要调用的回调函数。默认值为 None。
示例代码:
```python
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("通知标题", "通知内容", duration=10)
```
Python winrt 利用xml创建windows10 Toast通知中监听按钮被点击
要在 Windows 10 Toast 通知中添加一个监听按钮被点击的事件,可以使用 Python winrt 库和 XML 构建器创建一个包含自定义按钮的通知。下面是一个简单的示例代码:
```python
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
# 创建 ToastNotificationManager 对象
toaster = notifications.ToastNotificationManager
# 创建 ToastNotification 对象
toast = toaster.get_template_content(notifications.ToastTemplateType.ToastText02)
# 获取 Toast 的 XML 节点
xml = dom.XmlDocument()
xml.load_xml(toast.get_xml().get_xml())
# 添加一个按钮
actions = xml.getElementsByTagName("actions")[0]
action = xml.createElement("action")
action.setAttribute("content", "点击这里")
action.setAttribute("arguments", "buttonClicked")
action.setAttribute("activationType", "background")
actions.appendChild(action)
# 创建 ToastNotification 对象并显示
toast.add_node(xml)
notifier = notifications.ToastNotificationManager.create_toast_notifier()
notifier.show(toast)
```
在上面的代码中,我们使用 `ToastNotificationManager` 对象创建了一个基本的 Toast 通知模板。然后,我们使用 `XmlDocument` 对象加载了该模板的 XML,以便能够修改它。我们通过 `getElementsByTagName` 方法获取到了 `actions` 节点,然后创建了一个新的 `action` 节点来表示监听按钮被点击的事件。我们设置了按钮的 `content`、`arguments` 和 `activationType` 属性。最后,我们将修改后的 XML 内容添加回 `ToastNotification` 对象中,并使用 `ToastNotificationManager` 创建了一个 `ToastNotifier` 对象并显示了通知。