简年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("<b>Message</b>", fetch_message(), None).show()

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

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
发送通知菜单

为程序添加窗口

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

#!/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()
菜单
窗口

设置动态图标

除了以上这些,有时候我们还需要动态地设置托盘图标,以表现程序运行状态。直接重置图标的值即可,下面是在托盘区域显示 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()

参考资料

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341

推荐阅读更多精彩内容