Skip to content

Instantly share code, notes, and snippets.

@johnlane

johnlane/menu2.py

Created Feb 24, 2017
Embed
What would you like to do?
#!/usr/bin/env python
import gi
gi.require_version('Gtk','3.0')
gi.require_version('Keybinder', '3.0')
from gi.repository import Gtk, Gdk, Keybinder
class MenuBar(Gtk.Window):
def __init__(self, *args):
super().__init__(*args, name="bar")
# Create an undecorated dock
self.set_type_hint(Gdk.WindowTypeHint.DOCK)
self.set_decorated(False)
self.connect("delete-event", Gtk.main_quit)
action_group = Gtk.ActionGroup("my_actions")
action_group.add_actions([
("numbers", None, "Numbers", None, None, None),
("one", None, "One", None, None, self.callback),
("two", None, "Two", None, None, self.callback),
("shapes", None, "Shapes", None, None, None),
("triangle", None, "Triangle", None, None, self.callback),
("square", None, "Square", None, None, self.callback)
])
uimanager = Gtk.UIManager()
uimanager.insert_action_group(action_group)
uimanager.add_ui_from_string("""
<ui>
<menubar name='MenuBar'>
<menu name='default' action='numbers'>
<menuitem action='one' />
<menuitem action='two' />
</menu>
<menu action='shapes'>
<menuitem action='triangle' />
<menuitem action='square' />
</menu>
</menubar>
</ui>
""")
box = Gtk.Box();
menubar = uimanager.get_widget("/MenuBar")
box.pack_start(menubar, False, False, 0)
self.add(box)
item = Gtk.MenuItem()
item.set_label('Colours')
menu = Gtk.Menu()
self.menu = menu
item.set_submenu(menu)
menubar.append(item)
item = Gtk.MenuItem()
item.set_label('Red')
item.connect('activate',self.callback)
menu.append(item)
item = Gtk.MenuItem()
item.set_label('Blue')
item.connect('activate',self.callback)
menu.add(item)
# Bind hotkey
keystr = "Menu"
Keybinder.init()
Keybinder.bind(keystr, self.keybinder_callback, "Keystring %s (user data)" % keystr)
# For keybinder_callback
self.anchor = box # popup_at_widget
self.menubar = menubar
self.menu = uimanager.get_widget("/MenuBar/default")
def callback(self, obj):
print("You chose %s (%s)" % (obj.get_label(), type(obj)))
def keybinder_callback(self, keystr, user_data):
print("Handling", keystr, user_data)
print("Event time:", Keybinder.get_current_event_time())
#self.menu.popup(None,None,None,None,1,Keybinder.get_current_event_time())
#self.menu.popup_at_widget(self.anchor,Gdk.Gravity.SOUTH_WEST,Gdk.Gravity.NORTH_WEST,None)
self.menubar.select_item(self.menu)
MenuBar().show_all()
# Control-C termination https://bugzilla.gnome.org/show_bug.cgi?id=622084
from gi.repository import GLib
GLib.MainLoop().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment