AppIndicator3:從檔案名稱或 GdkPixbuf 設定指示器圖標

AppIndicator3:從檔案名稱或 GdkPixbuf 設定指示器圖標

我正在寫一個小的Python 3應用程式它用於AppIndicator3在頂部欄中放置一個圖標,然後更改該圖標以響應用戶操作。很簡單,對吧?由於該應用程式很小,因此需要從來源目錄運行,無需任何安裝。

問題是AppIndicator3.set_icon()需要str帶有圖標名稱,而不是該圖標的路徑。

我該如何說服 AppIndicator3 讓我給它一個檔案名稱或一個Pixbuf?或者,如何將我的圖標目錄新增至圖標名稱搜尋路徑? (我嘗試過AppIndicator3.set_icon_theme_path(),但我的圖標名稱仍然無法識別。

答案1

要使用小路最好用一個例子來說明圖示。在下面的範例中,我將圖示保留在與腳本(指示器)相同的目錄中,這對於您的情況來說似乎是一個方便的解決方案。

最重要的是,一旦您啟動了指標:

class Indicator():
    def __init__(self):
        self.app = "<indicator_name>"
        iconpath = "/path/to/initial/icon/"

        -------------------------------

        self.testindicator = AppIndicator3.Indicator.new(
        self.app, iconpath,
        AppIndicator3.IndicatorCategory.OTHER)

        -------------------------------

您可以使用以下命令更改圖示:

        self.testindicator.set_icon("/path/to/new/icon/")

在此輸入影像描述在此輸入影像描述

例子

在下面的範例中,所有圖示 、nocolor.pngpurple.pnggreen.png與腳本儲存在一起,但圖示的路徑設定為

currpath = os.path.dirname(os.path.realpath(__file__))

可以在任何地方。

#!/usr/bin/env python3
import os
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3

currpath = os.path.dirname(os.path.realpath(__file__))

class Indicator():
    def __init__(self):
        self.app = 'show_proc'
        iconpath = currpath+"/nocolor.png"
        # after you defined the initial indicator, you can alter the icon!
        self.testindicator = AppIndicator3.Indicator.new(
            self.app, iconpath,
            AppIndicator3.IndicatorCategory.OTHER)
        self.testindicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)       
        self.testindicator.set_menu(self.create_menu())

    def create_menu(self):
        menu = Gtk.Menu()
        item_quit = Gtk.MenuItem(label='Quit')
        item_quit.connect('activate', self.stop)
        item_green = Gtk.MenuItem(label='Green')
        item_green.connect('activate', self.green)
        item_purple = Gtk.MenuItem(label='Purple')
        item_purple.connect('activate', self.purple)
        menu.append(item_quit)
        menu.append(item_green)
        menu.append(item_purple)
        menu.show_all()
        return menu

    def stop(self, source):
        Gtk.main_quit()

    def green(self, source):
        self.testindicator.set_icon(currpath+"/green.png")

    def purple(self, source):
        self.testindicator.set_icon(currpath+"/purple.png")

Indicator()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()

筆記

....如果您需要更新圖標第二個線程,你需要使用

GObject.threads_init()

Gtk.main()

並且您需要使用以下方法更新介面(圖標或指示符文字):

GObject.idle_add()

如所應用的,例如這裡這裡

相關內容