pythonlinuxsystray

Set icon in front of menu entry in systray app


is it possible to set a custom icon in front of the menu entries "Top Menu, Middle Menu, Last Menu" in the systray app below?

#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx
import sys

TRAY_TOOLTIP = 'Tray App'
TRAY_ICON = '/usr/share/icons/hicolor/32x32/apps/distributor.png'

def create_menu_item(menu, label, func):
    item = wx.MenuItem(menu, -1, label)
    menu.Bind(wx.EVT_MENU, func, id=item.GetId())
    menu.AppendItem(item)
    return item

class TaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        self.frame = frame
        super(TaskBarIcon, self).__init__()
        self.set_icon(TRAY_ICON)

    def CreatePopupMenu(self):
        menu = wx.Menu()

        # Top Menu
        create_menu_item(menu, 'Top Menu', self.TopMenu)
        menu.AppendSeparator()

        # Middle Menu
        create_menu_item(menu, 'Middle Menu', self.MiddleMenu)

        # exit and Info
        menu.AppendSeparator()
        create_menu_item(menu, 'Last Menu', self.LastMenu)

        create_menu_item(menu, 'Exit', self.ExitMenu)

        return menu

    def set_icon(self, path):
        icon = wx.IconFromBitmap(wx.Bitmap(path))
        self.SetIcon(icon, TRAY_TOOLTIP)

    def TopMenu(self, event):
        print 'This is from Top Menu!'

    def MiddleMenu(self, event):
        print 'This is from Middle Menu!'

    def LastMenu(self, event):
        print 'This is from Last Menu!'

    def ExitMenu(self, event):
        wx.CallAfter(self.Destroy)
        self.frame.Close()

class App(wx.App):
    def OnInit(self):
        frame=wx.Frame(None)
        self.SetTopWindow(frame)
        TaskBarIcon(frame)
        return True

def main():
    app = App(False)
    app.MainLoop()


if __name__ == '__main__':
    main()

I have tried to find something like, but I couldn't find anything relevant. I saw that C# allows to set icons in front of the menu entry, but I am not sure if it applies for python as well. Thanks for your help and attention.


Solution

  • After some research, trial and error, I discovered that I have to use the variable icon on the definition of the menu:

    def create_menu_item(menu, label, func, icon=None):
        item = wx.MenuItem(menu, -1, label)
        if icon:
            item.SetBitmap(wx.Bitmap(icon))
        menu.Bind(wx.EVT_MENU, func, id=item.GetId())
        menu.AppendItem(item)
        return item
    

    And include the path to the icon on the definition of the menu entry :

            create_menu_item(menu, 'Title', self.Title, icon='icon.png')
    

    Result: enter image description here