简年7:手摸手教你制作通用 Linux 托盘应用

本文接着前几天那两篇《为 shell 脚本添加交互界面》和《一行代码实现通用 Linux 桌面通知》,进一步介绍如何在 Linux 下制作托盘图标,实现驻留在系统托盘区域的程序。

最简单的托盘程序

因为没有找到使用 shell 工具实现的托盘工具,所以就使用 Python 实现了。

# 导入 signal 以便后面使用 ctrl-c 关掉程序。
import signal
# 导入 Gtk 和 AppIndicator3,什么用的一眼就能看出来。
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator

# 使用的参数和前面那篇 zenity 的类似,无非就是“名称”、“分类”这些。
APPINDICATOR_ID = 'myappindicator'

def main():
    indicator = appindicator.Indicator.new(APPINDICATOR_ID, 'whatever', appindicator.IndicatorCategory.SYSTEM_SERVICES)
    indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
    indicator.set_menu(gtk.Menu())
    gtk.main()

# 为了方便在终端关闭程序而加上的代码
if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()

直接保存为 base.py 然后使用 python 运行即可(我是 Python 3 环境)。


没有图标的托盘演示

添加菜单

现在只是有了个图标,接下来要为托盘程序添加菜单:

import signal
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator

APPINDICATOR_ID = 'myappindicator'

def main():
    indicator = appindicator.Indicator.new(APPINDICATOR_ID, 'whatever', appindicator.IndicatorCategory.SYSTEM_SERVICES)
    indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
    indicator.set_menu(build_menu())
    gtk.main()

def build_menu():
    menu = gtk.Menu()
    item_quit = gtk.MenuItem('退出')
    item_quit.connect('activate', quit)
    menu.append(item_quit)
    menu.show_all()
    return menu

def quit(source):
    gtk.main_quit()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
添加一个菜单项

自定义图标

现在默认的图标是图片没找到的图片,所以接下来我们自定义图标,先去 icons 目录随便找张 svg 来充数,笑。

import os
import signal
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator

APPINDICATOR_ID = 'myappindicator'

def main():
    indicator = appindicator.Indicator.new(APPINDICATOR_ID, os.path.abspath('my_icon.svg'), appindicator.IndicatorCategory.SYSTEM_SERVICES)
    indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
    indicator.set_menu(build_menu())
    gtk.main()

def build_menu():
    menu = gtk.Menu()
    item_quit = gtk.MenuItem('退出')
    item_quit.connect('activate', quit)
    menu.append(item_quit)
    menu.show_all()
    return menu

def quit(source):
    gtk.main_quit()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
自定义图标

添加通知气泡功能

很多时候我们需要发送通知到桌面提醒用户,这里用到的是 Python 的包,实际上通过 Python 调用 zenity 命令也是可以的。

import os
import signal
import json

from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify


APPINDICATOR_ID = 'myappindicator'

def main():
    indicator = appindicator.Indicator.new(APPINDICATOR_ID, os.path.abspath('my_icon.svg'), appindicator.IndicatorCategory.SYSTEM_SERVICES)
    indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
    indicator.set_menu(build_menu())
    notify.init(APPINDICATOR_ID)
    gtk.main()

def build_menu():
    menu = gtk.Menu()
    item_message = gtk.MenuItem('通知')
    item_message.connect('activate', message)
    menu.append(item_message)
    item_quit = gtk.MenuItem('退出')
    item_quit.connect('activate', quit)
    menu.append(item_quit)
    menu.show_all()
    return menu

def fetch_message():
    return "hello world"

def message(_):
    notify.Notification.new("Message", fetch_message(), None).show()

def quit(_):
    notify.uninit()
    gtk.main_quit()

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
简年7:手摸手教你制作通用 Linux 托盘应用_第1张图片
发送通知菜单

为程序添加窗口

有了基本的图标、菜单、通知,有时候还需要一些窗口显示更丰富的界面。
下面代码中调整了之前的例子:

#!/usr/bin/env python3.3

from gi.repository import Gtk
from gi.repository import AppIndicator3 as appindicator

class MyIndicator:
  def __init__(self, root):
    self.app = root
    self.ind = appindicator.Indicator.new(
                self.app.name,
                "indicator-messages",
                appindicator.IndicatorCategory.APPLICATION_STATUS)
    self.ind.set_status (appindicator.IndicatorStatus.ACTIVE)
    self.menu = Gtk.Menu()
    item = Gtk.MenuItem()
    item.set_label("程序窗口")
    item.connect("activate", self.app.main_win.cb_show, '')
    self.menu.append(item)

    item = Gtk.MenuItem()
    item.set_label("配置")
    item.connect("activate", self.app.conf_win.cb_show, '')
    self.menu.append(item)

    item = Gtk.MenuItem()
    item.set_label("退出")
    item.connect("activate", self.cb_exit, '')
    self.menu.append(item)

    self.menu.show_all()
    self.ind.set_menu(self.menu)

  def cb_exit(self, w, data):
     Gtk.main_quit()

class MyConfigWin(Gtk.Window):
  def __init__(self, root):
    super().__init__()
    self.app = root
    self.set_title(self.app.name + ' 配置窗口')

  def cb_show(self, w, data):
    self.show()

class MyMainWin(Gtk.Window):
  def __init__(self, root):
    super().__init__()
    self.app = root
    self.set_title(self.app.name)

  def cb_show(self, w, data):
    self.show()

class MyApp(Gtk.Application):
  def __init__(self, app_name):
    super().__init__()
    self.name = app_name
    self.main_win = MyMainWin(self)
    self.conf_win = MyConfigWin(self)
    self.indicator = MyIndicator(self)

  def run(self):
    Gtk.main()

if __name__ == '__main__':
  app = MyApp('测试应用')
  app.run()
简年7:手摸手教你制作通用 Linux 托盘应用_第2张图片
菜单
简年7:手摸手教你制作通用 Linux 托盘应用_第3张图片
窗口

设置动态图标

除了以上这些,有时候我们还需要动态地设置托盘图标,以表现程序运行状态。直接重置图标的值即可,下面是在托盘区域显示 CPU 使用情况的例子:

from gi.repository import Gtk, GLib

try: 
       from gi.repository import AppIndicator3 as AppIndicator  
except:  
       from gi.repository import AppIndicator

import re

class IndicatorCPUSpeed:
    def __init__(self):
        # param1: identifier of this indicator
        # param2: name of icon. this will be searched for in the standard them
        # dirs
        # finally, the category. We're monitoring CPUs, so HARDWARE.
        self.ind = AppIndicator.Indicator.new(
                            "indicator-cpuspeed", 
                            "onboard-mono",
                            AppIndicator.IndicatorCategory.HARDWARE)

        # some more information about the AppIndicator:
        # http://developer.ubuntu.com/api/ubuntu-12.04/python/AppIndicator3-0.1.html
        # http://developer.ubuntu.com/resources/technologies/application-indicators/

        # need to set this for indicator to be shown
        self.ind.set_status (AppIndicator.IndicatorStatus.ACTIVE)

        # have to give indicator a menu
        self.menu = Gtk.Menu()

        # you can use this menu item for experimenting
        item = Gtk.MenuItem()
        item.set_label("Test")
        item.connect("activate", self.handler_menu_test)
        item.show()
        self.menu.append(item)

        # this is for exiting the app
        item = Gtk.MenuItem()
        item.set_label("Exit")
        item.connect("activate", self.handler_menu_exit)
        item.show()
        self.menu.append(item)

        self.menu.show()
        self.ind.set_menu(self.menu)

        # initialize cpu speed display
        self.update_cpu_speeds()
        # then start updating every 2 seconds
        # http://developer.gnome.org/pygobject/stable/glib-functions.html#function-glib--timeout-add-seconds
        GLib.timeout_add_seconds(2, self.handler_timeout)

    def get_cpu_speeds(self):
        """Use regular expression to parse speeds of all CPU cores from
        /proc/cpuinfo on Linux.
        """

        f = open('/proc/cpuinfo')
        # this gives us e.g. ['2300', '2300']
        s = re.findall('cpu MHz\s*:\s*(\d+)\.', f.read())
        # this will give us ['2.3', '2.3']
        f = ['%.1f' % (float(i) / 1000,) for i in s]
        return f

    def handler_menu_exit(self, evt):
        Gtk.main_quit()

    def handler_menu_test(self, evt):
        # we can change the icon at any time
        self.ind.set_icon("indicator-messages-new")

    def handler_timeout(self):
        """This will be called every few seconds by the GLib.timeout.
        """
        # read, parse and put cpu speeds in the label
        self.update_cpu_speeds()
        # return True so that we get called again
        # returning False will make the timeout stop
        return True

    def update_cpu_speeds(self):
        f = self.get_cpu_speeds()
        self.ind.set_label(' '.join(f), "8.8 8.8 8.8 8.8")

    def main(self):
        Gtk.main()

if __name__ == "__main__":
    ind = IndicatorCPUSpeed()
    ind.main()

参考资料

  • The Python GTK+ 3 Tutorial
  • https://github.com/candidtim/vagrant-appindicator

除了 Python,还可以使用 Electron 实现,不过 Electron 打包运行实在不小,我就不玩了,而且文档好少。当然 Qt 啦什么的也可以,但是我不会呀。

话说回来,要是有一个像 zenity 这样可以直接用 shell 生成托盘应用的工具那就太好了,如果你知道请务必评论留言啊~~

你可能感兴趣的:(简年7:手摸手教你制作通用 Linux 托盘应用)