Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import gtk, os, sys
- def print_usage():
- print "Usage:"
- print "PyMenu label:command[:icon] ..."
- print "The label:command:icon tuple can appear multiple times."
- print "icon is a string identifier of a gtk stock icon. You can, for example, use either 'new' or 'gtk-new'."
- exit()
- def _generate_callback(command):
- """
- Generates a callback for a menu item.
- """
- def callback(menuitem):
- os.system(command+" &")
- exit()
- return callback
- def _create_normal_menu_item(text):
- """
- Internal method; creates standart gtk.MenuItem
- """
- item = gtk.MenuItem(text)
- return item
- def _create_stock_menu_item(text, stock_id):
- """
- Internal method; creates a menu item from stock - gtk.ImageMenuItem, but replaces the stock text
- """
- if not stock_id.startswith("gtk-"):
- stock_id = "gtk-"+stock_id
- stock_lookup = gtk.stock_lookup(stock_id)
- if not stock_lookup:
- print "Warning: Stock_id", stock_id, "not found"
- item = gtk.ImageMenuItem(stock_id)
- label = item.get_children()[0]
- label.set_text(text)
- return item
- def create_menu_item(entry):
- """
- Creates a menu item, with or without a stock icon.
- """
- label = entry["label"]
- command = entry["command"]
- if "icon" in entry:
- icon = entry["icon"]
- else:
- icon = None
- item = None
- if icon:
- item = _create_stock_menu_item(label, icon)
- else:
- item = _create_normal_menu_item(label)
- item.connect("activate", _generate_callback(command))
- return item
- def parse_args(args):
- """
- Parses the command line arguments. Each entry is saved as a dict.
- """
- entries = []
- for arg in args:
- entry = {}
- if ":" not in arg:
- print "Misformatted argument:", arg
- print_usage()
- entry_raw = arg.split(':')
- if len(entry_raw)!=2 and len(entry_raw)!=3:
- print "Misformatted argument:", arg
- print_usage()
- entry["label"] = entry_raw[0]
- entry["command"] = entry_raw[1]
- if len(entry_raw)==3:
- entry["icon"] = entry_raw[2]
- entries.append(entry)
- return entries
- def create_menu(entries):
- menu = gtk.Menu()
- for entry in entries:
- menu.append(create_menu_item(entry))
- menu.connect("deactivate", gtk.main_quit)
- menu.show_all()
- return menu
- if __name__ == "__main__":
- if len(sys.argv)==1 or sys.argv[1]=="-h" or sys.argv[1]=="--help":
- print_usage()
- entries = parse_args(sys.argv[1:])
- menu = create_menu(entries)
- menu.popup(None, None, None, 0, 0)
- gtk.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement