【发布时间】:2013-04-02 00:29:03
【问题描述】:
我想知道如何使用 python 创建系统托盘弹出消息。我已经在很多软件中看到了这些,但很难找到资源来轻松使用任何语言进行操作。任何人都知道一些在 Python 中执行此操作的库?
【问题讨论】:
标签: python notifications popup system-tray
我想知道如何使用 python 创建系统托盘弹出消息。我已经在很多软件中看到了这些,但很难找到资源来轻松使用任何语言进行操作。任何人都知道一些在 Python 中执行此操作的库?
【问题讨论】:
标签: python notifications popup system-tray
在pywin32 library 的帮助下,您可以使用我找到的以下示例代码here:
from win32api import *
from win32gui import *
import win32con
import sys, os
import struct
import time
class WindowsBalloonTip:
def __init__(self, title, msg):
message_map = {
win32con.WM_DESTROY: self.OnDestroy,
}
# Register the Window class.
wc = WNDCLASS()
hinst = wc.hInstance = GetModuleHandle(None)
wc.lpszClassName = "PythonTaskbar"
wc.lpfnWndProc = message_map # could also specify a wndproc.
classAtom = RegisterClass(wc)
# Create the Window.
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
self.hwnd = CreateWindow( classAtom, "Taskbar", style, \
0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
0, 0, hinst, None)
UpdateWindow(self.hwnd)
iconPathName = os.path.abspath(os.path.join( sys.path[0], "balloontip.ico" ))
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
try:
hicon = LoadImage(hinst, iconPathName, \
win32con.IMAGE_ICON, 0, 0, icon_flags)
except:
hicon = LoadIcon(0, win32con.IDI_APPLICATION)
flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "tooltip")
Shell_NotifyIcon(NIM_ADD, nid)
Shell_NotifyIcon(NIM_MODIFY, \
(self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
hicon, "Balloon tooltip",msg,200,title))
# self.show_balloon(title, msg)
time.sleep(10)
DestroyWindow(self.hwnd)
def OnDestroy(self, hwnd, msg, wparam, lparam):
nid = (self.hwnd, 0)
Shell_NotifyIcon(NIM_DELETE, nid)
PostQuitMessage(0) # Terminate the app.
def balloon_tip(title, msg):
w=WindowsBalloonTip(title, msg)
if __name__ == '__main__':
balloon_tip("Title for popup", "This is the popup's message")
【讨论】:
lpszClassName 分配一个随机类名。如果您按原样运行该示例,它将仅显示一个气泡帮助,然后在下一次尝试失败并显示pywintypes.error: (1410, 'RegisterClass', 'Class already exists')。作为快速破解,我使用了from uuid import uuid4 并在名称中添加了uuid4()。
我最近使用Plyer 包创建了跨平台通知,使用Notification 外观(它还有许多其他有趣的东西值得一看)。
很容易使用:
from plyer.utils import platform
from plyer import notification
notification.notify(
title='Here is the title',
message='Here is the message',
app_name='Here is the application name',
app_icon='path/to/the/icon.' + ('ico' if platform == 'win' else 'png')
)
【讨论】:
python27_x64\lib\site-packages\plyer\platforms\win\libs\balloontip.py", line 145, in balloon_tip 的错误,方法为WindowsBalloonTip(**kwargs),错误消息是:TypeError: __init__() got an unexpected keyword argument 'ticker'。它是带有 python 2.7 的 windows7。
pip install -I https://github.com/kivy/plyer/zipball/master
【讨论】:
您将需要使用第 3 方 python GUI 库或 pywin32 库。 TkInter,python自带的GUI工具包,不支持系统托盘弹出。
支持使用系统托盘的多种中性库:
支持使用系统托盘的 Windows 特定库:
在 windows 上使用 wxpython 弹出系统托盘的信息/示例:
【讨论】:
Windows
现在有一种使用Python/Winrt 的官方方法来实现这一点,github 解释了如何将 UWP API 映射到 python 的。
通过关注official UWP documentation,我设法显示了一个小通知,该通知也出现在 Windows 通知中心:
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
#create notifier
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier();
#define your notification as string
tString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Sample toast</text>
<text>Sample content</text>
</binding>
</visual>
</toast>
"""
#convert notification to an XmlDocument
xDoc = dom.XmlDocument()
xDoc.load_xml(tString)
#display notification
notifier.show(notifications.ToastNotification(xDoc))
设置仅限于库的安装
pip install winrt
要求
Windows 10,2018 年 10 月更新或更高版本
适用于 Windows 的 Python,版本 3.7 或更高版本
pip,版本 19 或更高版本
奖励 macOS
我还找到了一种在 macOS 中使用 AppleScript 的方法,以下代码的目标是构建将通过 python os.system 执行的 AppleScript 代码
import os
def displayNotification(message,title=None,subtitle=None,soundname=None):
"""
Display an OSX notification with message title an subtitle
sounds are located in /System/Library/Sounds or ~/Library/Sounds
"""
titlePart = ''
if(not title is None):
titlePart = 'with title "{0}"'.format(title)
subtitlePart = ''
if(not subtitle is None):
subtitlePart = 'subtitle "{0}"'.format(subtitle)
soundnamePart = ''
if(not soundname is None):
soundnamePart = 'sound name "{0}"'.format(soundname)
appleScriptNotification = 'display notification "{0}" {1} {2} {3}'.format(message,titlePart,subtitlePart,soundnamePart)
os.system("osascript -e '{0}'".format(appleScriptNotification))
使用 asis :
displayNotification("message","title","subtitle","Pop")
结语
我把前面所有的代码总结成两个要点
【讨论】:
在Linux系统中,你可以使用内置命令notify-send。
ntfy 库可用于发送推送通知。
click here for ntfy documentation
安装:
sudo pip install ntfy
例子:
ntfy send "your message!"
ntfy -t "your custom title" send "your message"
【讨论】:
最简单的方法是使用win10toast
这是代码:
from win10toast import ToastNotifier
Notifi = ToastNotifier()
Notifi.show_toast("Title", "Description")
这可能会对你有所帮助!
【讨论】: