如何使用python创建系统托盘弹出消息?(视窗)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15921203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:22:29  来源:igfitidea点击:

How to create a system tray popup message with python? (Windows)

pythonpopupsystem-tray

提问by Roman Rdgz

I'd like to know how to create a system tray popup message with python. I have seen those in lots of softaware, but yet difficult to find resources to do it easily with any language. Anyone knows some library for doing this in Python?

我想知道如何使用 python 创建系统托盘弹出消息。我已经在很多软件中看到过这些,但很难找到使用任何语言轻松完成的资源。任何人都知道一些库可以在 Python 中执行此操作吗?

采纳答案by halex

With the help of the pywin32libraryyou can use the following example code I found here:

pywin32的帮助下,您可以使用我在此处找到的以下示例代码:

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")

回答by cnodell

You will need to use a 3rd party python GUI library or the pywin32 library. TkInter, the GUI toolkit that comes bundled with python does not support system tray pop ups.

您将需要使用第 3 方 python GUI 库或 pywin32 库。TkInter,python 自带的 GUI 工具包不支持系统托盘弹出窗口。

Multiform neutral libraries that support working with the system tray:

支持使用系统托盘的多形式中性库:

  • wxPython
  • PyGTK
  • PyQT
  • 蟒蛇
  • PyGTK
  • PyQT

Windows specific library that supports working with the system tray:

支持使用系统托盘的 Windows 特定库:

  • pywin32
  • pywin32

Information/example of system tray pop ups using wxpython on windows:

在 Windows 上使用 wxpython 弹出系统托盘的信息/示例:

回答by Epoc

I recently used the Plyerpackage to create cross-platform notifications without pain, using the Notificationfacade (it have many other interesting things that are worth to take a look at).

我最近使用Plyer轻松创建跨平台通知,使用NotificationFacade(它有许多其他有趣的东西值得一看)。

Pretty easy to use:

非常容易使用:

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.png'
)

回答by jeevan

in Linux system , You could use inbuilt command notify-send.

在 Linux 系统中,您可以使用内置命令notify-send

ntfylibrary can be used for sending push notifications.

ntfy库可用于发送推送通知。

click here for ntfy documentation

单击此处获取 ntfy 文档

installation:

安装:

sudo pip install ntfy

examples:

例子:

ntfy send "your message!"
ntfy send -t "your custom title" "your message"

回答by Ananth Kumar Vasamsetti

Here is the simple way to show notifications on windows 10 using python: module win10toast.

这是使用 python 在 Windows 10 上显示通知的简单方法:module win10toast

Requirements:

要求

  • pypiwin32
  • setuptools
  • pypiwin32
  • 设置工具

Installation:

安装

>> pip install win10toast

Example:

示例

from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Demo notification",
                   "Hello world",
                   duration=10)

Resultant of the code

代码的结果

回答by Marc_Alx

Windows

视窗

There's now an official way to achieve that using Python/Winrt, the github explains how to map UWP API to python ones.

现在有一种使用Python/Winrt实现这一目标的官方方法,github 解释了如何将 UWP API 映射到 Python API。

By following the official UWP documentationI've managed to display a small notification that also appears in Windows notification center :

通过遵循官方 UWP 文档,我设法显示了一个小通知,该通知也出现在 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))

The setup is limited to the installation of the library

设置仅限于库的安装

pip install winrt

Requirements

要求

Windows 10, October 2018 Update or later

Windows 10,2018 年 10 月更新或更高版本

Python for Windows, version 3.7 or later

适用于 Windows 的 Python,版本 3.7 或更高版本

pip, version 19 or later

pip,版本 19 或更高版本

Bonus macOS

额外的 macOS

I've also found a way to do it in macOS by using AppleScript, the goal of the following code is to build an AppleScript code that will be executed via python os.system

我还找到了一种使用 AppleScript 在 macOS 中执行此操作的方法,以下代码的目标是构建将通过 python 执行的 AppleScript 代码 os.system

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))

Use asis :

使用 asis :

displayNotification("message","title","subtitle","Pop")

Final notes

最后的笔记

I've sum up all the previous code in two gists

我已经总结了两个要点中的所有以前的代码

Windows

视窗

macOS

苹果系统