infi.systray
infi.systray is a Python library that provides an easy way to create a system tray icon for Windows applications. It allows adding custom menus and actions, handling clicks, and managing the icon's lifecycle. Current version is 0.1.12.1, with releases occurring infrequently for maintenance or minor updates.
Warnings
- gotcha infi.systray is strictly a Windows-only library. It relies on Windows API calls and will not function on macOS, Linux, or any other operating system.
- gotcha The `SysTrayIcon.start()` method is blocking. It will run the message loop on the current thread, preventing other code from executing until the tray icon is explicitly quit. For applications requiring responsiveness or other concurrent tasks, `SysTrayIcon` must be run in a separate thread.
- gotcha The `SysTrayIcon` constructor requires a valid path to an icon file (.ico) or a resource identifier (e.g., `C:\Windows\System32\shell32.dll,1`). Providing an invalid path or a non-existent file will result in an error or a missing icon.
Install
-
pip install infi.systray
Imports
- SysTrayIcon
from infi.systray import SysTrayIcon
Quickstart
import os
import sys
from infi.systray import SysTrayIcon
# This quickstart is designed for Windows environments ONLY,
# as infi.systray relies on Windows API calls.
# Define menu options and callbacks
def on_hello(systray_instance):
print("Hello menu item clicked!")
def on_goodbye(systray_instance):
print("Goodbye menu item clicked!")
def on_quit_callback(systray_instance):
print("Exiting application from tray icon...")
# It's crucial to force exit because systray.start() is blocking.
os._exit(0) # Terminate the process
# Define the menu structure: (MenuItemText, IconPathForMenuItem, CallbackFunction)
menu_options = (
("Hello", None, on_hello),
("Goodbye", None, on_goodbye),
)
# Specify an icon. For a runnable example on Windows without external files,
# we can use a system-provided icon from a DLL. 'shell32.dll,1' often points
# to a generic application icon.
# NOTE: This path is Windows-specific.
icon_source = r"C:\Windows\System32\shell32.dll,1"
print("Starting infi.systray application...")
print("Look for an icon in your Windows system tray (usually bottom-right).")
print("Right-click the icon to see the menu. Select 'Quit' to terminate.")
# Create the SysTrayIcon instance
systray = SysTrayIcon(
icon_source,
"My infi.systray App", # Text displayed when hovering over the icon
menu_options,
on_quit=on_quit_callback,
default_menu_index=0 # Double-click action (e.g., triggers first menu item)
)
# Start the system tray icon. This call blocks the current thread until the
# on_quit_callback is triggered and calls os._exit(0).
systray.start()
print("Application has stopped.") # This line is generally not reached due to os._exit(0)