Have you ever wondered how to create those little status icons in the Windows System Tray that usually appear on the lower right of your screen? The wxPython toolkit provides a pretty simple way to do just that and this article will walk you through the process.

Working the Code

For reasons I don’t quite understand, the wx component we want is wx.TaskBarIcon. I assume it’s called that because the System Tray is part of the TaskBar or maybe they don’t differentiate between the TaskBar and the tray area in other operating systems. Anyway, first you need an icon to use. You can get your image wherever you like. In this example, we’re going to use an an “envelope” image that I turned into Python code using wxPython’s handy img2py utility. When you run an image through img2py, you’ll end up with something like this:

#----------------------------------------------------------------------
# This file was generated by img2py.py
#
from wx import ImageFromStream, BitmapFromImage
from wx import EmptyIcon
import cStringIO, zlib
 
 
def getData():
    return zlib.decompress(
'x\xda\x01\x86\x01y\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\
\x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\
\x08d\x88\x00\x00\x01=IDATX\x85\xed\x97[\x9a\x83 \x0c\x85Ol\xf7\x1566#\xec\
\xac,\xace\x1e\xe4b \xfa\xa9\xa3\xe5\xc5<\x15$9\x7fO\xc0\x0b\xd1\xf0@\xcf\
\x18\xba\xaa\xdf\x007\x00\x80g\xfa1\xfe\xfe\x84o\x89ZkA\xc3\x83\x04\x00\x00\
\x8c\xe3x\xa1,\x01\x08p\xce\x89Y\xd1\x82\xfa\xe2y\xc2P\xc5\x1b\x00c\xcc\x05\
\x10Sg\x9ds0\xc6\xac\x030\xf3\x05\x10\x94\xc5\x99y\x1d\xe0\\\x88\xc9z\xe7l\
\x147\xea*\xf5\x18\xfe\x0fB\xf6\xbc\xfcs\xfd\x90-\xde\x07\x8eC\xc8\x9e\x17\
\xdbI]\xbdz#:\x06Q\xf7\xbc8\xb2\x1b`\x1f\xc4R\xcf\x83\xb8\xbe\x1b %\x16\x08\
\x12\xf3Z\xcfu\xe1\xdd\x0eL\x89\xde\xbf\xc0\xcc3\'lU\xb0=\xe7\xcc\x0c\xef\
\xfd\x02\x88\x8c\xa7:\x1b\x13\xbd\xf7\xd1\xca\x90\x0b\'\xb1:\x8a\xf8\xb4>A\
\x94|\xdd\x81E\x80)y~|(\x17\xd6\xa2\x15"0\x87\xe8`\xc9\xdf\x00@\xd9v\x19\xb2\
\xf0|}-<\x1f3\x9bXo\xe3\x1e(\xe2u\xcf\xea\xcd\xb4},\xf7\xc4\n@\xb1\xfd\x98\
\xd0\xdax\t\xa2y\x18\xb5q\x1e\xc8\xa6\x87\xd1\x99\xd6\xeb\xe3\xaaz\xfa0\xe9\
\xf5J\x96\x01\xc2\xe7\xfd5\x00\x00-@\xaf\xe8\xfeZ~\x03t\x07\xf8\x03\x82\xac\
\xa4VT\xfd\xcd\xa3\x00\x00\x00\x00IEND\xaeB`\x82\n\xa7\xa9\xa8' )
 
def getBitmap():
    return BitmapFromImage(getImage())
 
def getImage():
    stream = cStringIO.StringIO(getData())
    return ImageFromStream(stream)
 
def getIcon():
    icon = EmptyIcon()
    icon.CopyFromBitmap(getBitmap())
    return icon

The image data is all in the getData function. I am going to call this file “email_ico.py”. We’ll import it into our main program and call its getIcon method to acquire the icon we want to use. Let’s take a look at the main application now:

import wx
from mail_ico import getIcon
 
########################################################################
class MailIcon(wx.TaskBarIcon):
    TBMENU_RESTORE = wx.NewId()
    TBMENU_CLOSE   = wx.NewId()
    TBMENU_CHANGE  = wx.NewId()
    TBMENU_REMOVE  = wx.NewId()
 
    #----------------------------------------------------------------------
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
 
        # Set the image
        self.tbIcon = getIcon()
 
        self.SetIcon(self.tbIcon, "Test")
 
        # bind some events
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.OnTaskBarLeftClick)
 
    #----------------------------------------------------------------------
    def CreatePopupMenu(self, evt=None):
        """
        This method is called by the base class when it needs to popup
        the menu for the default EVT_RIGHT_DOWN event.  Just create
        the menu how you want it and return it from this function,
        the base class takes care of the rest.
        """
        menu = wx.Menu()
        menu.Append(self.TBMENU_RESTORE, "Open Program")
        menu.Append(self.TBMENU_CHANGE, "Show all the Items")
        menu.AppendSeparator()
        menu.Append(self.TBMENU_CLOSE,   "Exit Program")
        return menu
 
    #----------------------------------------------------------------------
    def OnTaskBarActivate(self, evt):
        """"""
        pass
 
    #----------------------------------------------------------------------
    def OnTaskBarClose(self, evt):
        """
        Destroy the taskbar icon and frame from the taskbar icon itself
        """
        self.frame.Close()
 
    #----------------------------------------------------------------------
    def OnTaskBarLeftClick(self, evt):
        """
        Create the right-click menu
        """
        menu = self.CreatePopupMenu()
        self.PopupMenu(menu)
        menu.Destroy()
 
########################################################################
class MyForm(wx.Frame):
 
    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(500,500))
        panel = wx.Panel(self)
        self.tbIcon = MailIcon(self)
        self.Bind(wx.EVT_CLOSE, self.onClose)
 
    #----------------------------------------------------------------------
    def onClose(self, evt):
        """
        Destroy the taskbar icon and the frame
        """
        self.tbIcon.RemoveIcon()
        self.tbIcon.Destroy()
        self.Destroy()
 
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm().Show()
    app.MainLoop()

The first class is basically copied straight out of the wxPython demo and simplified slightly. You can look there if you need a more complete example. Anyway, we bind a couple events in our sub-classed TaskBarIcon that allow us to close the application and show a menu, respectively. You will also note that we set the icon we created in the __init__ simply by calling its SetIcon method and passing in a string for its tooltip.

In the close method, we call the frame directly that we want it to close. A better method would be to use pubsub here. If you want to pause a moment and read about pubsub, I’ve written a little post about it too. The rest of the code is pretty self-explanatory.

Now we can move on to the wx.Frame sub-class. Here we basically just instantiate the TaskBarIcon class that we created earlier and we bind the frame to EVT_CLOSE. You might wonder about this. There are some got’chas with using the TaskBarIcon on Windows. If I just tell the frame to close, it closes just fine, but the icon remains and Python just kind of hangs in lala land. If you only allow the user to close using the task bar icon’s right-click menu, then you could just add a RemoveIcon method and a self.Destroy() there and you’d be good to go (for some reason, RemoveIcon isn’t enough to get rid of the TaskBarIcon, so you also need to tell it to Destroy itself too) But if you allow the user to press the little “x” in the upper right-hand corner, then you’ll need to catch EVT_CLOSE and deal with it appropriately. When you do catch this event, you can NOT just call self.Close() or you’ll end up in an infinite loop, which is why we call self.Destroy() instead.

Wrapping Up

Now you should be able to create your own TaskBarIcon application. I highly recommend looking at the wxPython demo to see what else you can do with it. I think adding an icon can add a bit of polish to your application, especially if you need to have it running hidden for a while and then make it pop-up at the user’s command.

Further Reading

Source

Print Friendly