- 1 year ago
windows toast notifications with action using python winrt module
To create Windows toast notifications with actions using the winrt
module in Python, you can follow these steps:
Install Required Packages:
First, make sure you have the necessary packages installed. Open a command prompt or terminal and run the following command to install thewinrt
andpywin32
packages:pip install winrt pywin32
Import Required Modules:
In your Python script, import the necessary modules:pythonimport winrt.windows.ui.notifications as notifications
from winrt.windows.ui.notifications import ToastNotification
from winrt.windows.data.xml.dom import XmlDocument
import winrt.windows.ui.notifications.toastnotifications as tnots
import winrt.windows.ui.notifications.toastnotificationmanager as tmanager
Create Toast Template:
Define the toast notification XML using theXmlDocument
class:pythontoast_xml = """
<toast>
<visual>
<binding template="ToastGeneric">
<text>Hello World</text>
<text>This is a toast notification with action.</text>
</binding>
</visual>
<actions>
<action arguments="action1" content="Action 1"/>
<action arguments="action2" content="Action 2"/>
</actions>
</toast>
"""
toast_dom = XmlDocument()
toast_dom.load_xml(toast_xml)
Register and Display the Toast Notification:
Register the toast notification and display it using theToastNotificationManager
:pythontmanager.ToastNotificationManager.create_toast_notifier().show(ToastNotification(toast_dom))
Handle Actions:
To handle the actions when the user interacts with the toast notification, you can set up an event listener using theEventWaitHandle
class from thepywin32
package:pythonimport win32event
event_handle = win32event.CreateEvent(None, 0, 0, None)
def on_action(event_args):
# Handle the action based on the argument value
action = event_args.args
print("Action clicked:", action)
toast_actions = tnots.ToastNotificationActionTriggerDetail.get_current()
toast_actions.add_action("action1", "Action 1")
toast_actions.add_action("action2", "Action 2")
toast_actions.on_triggered += on_action
win32event.WaitForSingleObject(event_handle, -1)
In this example, the
on_action
function handles the action clicked by the user. You can modify it to perform the desired action based on the argument value.
By following these steps, you should be able to create a Windows toast notification with actions using the winrt
module in Python. Customize the toast XML and action handling based on your requirements.