Wednesday, June 29, 2005

Python and the Windows System Tray

Continuing with my exploration of small neat and usefull python hacks for windows, I went searching the web for how to use python to write an app that would run on the Windows System Tray.

Shift over... its Googlistic All The Way :)

I came across this from Simon Brunning : http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html

Quickly downloaded it, and yesternite (yup... i'm becoming a Pythonire - that's a poor vampire spin off :D ), I took it for a Test Drive.

After a quick understanding of how it works, I tried to write a small app, and in the process I quickly refactored out a small library, that makes using it a bit more Intuitive to me.

The module which i dubbed 'systray' looks like this:

import SysTrayIcon

def default_onclick(s):
return

class SysTrayApp:
def __init__(self, title, icon=None):
self.icon = icon
self.title = title
self.menu = []

def start(self):
SysTrayIcon.SysTrayIcon(self.icon, self.title, tuple(self.menu) ,default_menu_index=1)
return

def add_menuitem(self, m):
self.menu.append(tuple(m))
#print tuple(self.menu)
return


class MenuItem(list):
def __init__(self, title):
list.__init__(self)
self.append(title)
self.append(None)
self.append(default_onclick)

def __set_icon(self, icon):
self[1] = icon

def __set_onclick(self, handler):
self[2] = handler

icon = property(None, __set_icon, None, "Icon Property")
onclick = property(None, __set_onclick, None, "OnClick Event Handler")


Easily use this module, you can do the following:

#-------------------------------

import systray



mitem_sample = systray.MenuItem('Sample Menu')

st_sample = systray.SysTrayApp('systray sample', 'default.ico')
st_sample.add_menuitem(mitem_sample)
st_sample.start()

#--------------------------------------


To add icons and menu actions to those menu items, modify the code as follows:

import systray



mitem_sample = systray.MenuItem('Sample Menu')
mitem_sample.icon = 'default.ico'

def sample_onclick(systrayicon):
systrayicon.title = "I have been clicked"
return

mitem_sample.onclick = sample_onclick

st_sample = systray.SysTrayApp('systray sample', 'default.ico')
st_sample.add_menuitem(mitem_sample)
st_sample.start()

#---------------------------------------------

Well, that's it.

I want to use this for some nifty utils, like a network monitoring daemon, a monitor for pmserv, etc.

hmm... fun times ahead i say.

1 Comments:

At Saturday, October 22, 2011 2:22:00 AM, Anonymous Anonymous said...

Thank you! This is very helpful and it works but of course only after you insert all the needed indentation inside the classes and function definitions.

 

Post a Comment

<< Home