Skip to content

Instantly share code, notes, and snippets.

@kernc
Created September 1, 2014 21:15
Show Gist options
  • Save kernc/43ccc45364107361dec1 to your computer and use it in GitHub Desktop.
Save kernc/43ccc45364107361dec1 to your computer and use it in GitHub Desktop.
Constructing multi-level GtkMenu by example of time zone hierarchy.
""" Constructing multi-level GtkMenu by example of time zone hierarchy.
The example below is missing a GtkWindow and a gtk.main() to work."""
import gtk
from collections import defaultdict
from commands import getoutput
def autovivified():
return defaultdict(autovivified)
def cb_selected(menuitem, data):
pass
hierarchy = autovivified()
for line in getoutput("awk '/^[^#]/{ print $3,$1 }' /usr/share/zoneinfo/zone.tab").split('\n'):
timezone, country_code = line.split()
submenu, parts = hierarchy, timezone.split('/')
for i, part in enumerate(parts, 1):
if i != len(parts): submenu = submenu[part]
else: submenu[part] = country_code
def _build_menu(d):
menu = gtk.Menu()
for k, v in d.items():
menuitem = gtk.MenuItem(k)
if isinstance(v, dict):
menuitem.set_submenu(_build_menu(v))
else:
menuitem.connect('activate', cb_selected, v)
menuitem.show()
menu.append(menuitem)
menu.show()
return menu
menu = _build_menu(hierarchy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment