I'm following the Python GTK+ 3 Tutorial, and the accelerators I'm putting for the toolbar actions don't work. Here's a program showing the problem, roughly based on that tutorial. There's a menu action with N
shortcut and a toolbar action with X
shortcut. Menu action's shorcut works, toolbar action's one doesn't, even though the actions are created identically.
from gi.repository import Gtk
UI_INFO = """
<ui>
<menubar name='TestMenubar'>
<menu action='FileMenu'>
<menuitem action='MenuAction' />
</menu>
</menubar>
<toolbar name='TestToolbar'>
<toolitem action='ToolbarAction' />
</toolbar>
</ui>
"""
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Test")
self.set_default_size(200, 100)
action_group = Gtk.ActionGroup(name="test_actions")
self.add_menu_action(action_group)
self.add_toolbar_action(action_group)
uimanager = self.create_ui_manager()
uimanager.insert_action_group(action_group)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
menubar = uimanager.get_widget("/TestMenubar")
box.pack_start(menubar, False, False, 0)
toolbar = uimanager.get_widget("/TestToolbar")
box.pack_start(toolbar, False, False, 0)
self.add(box)
def add_menu_action(self, action_group):
action_filemenu = Gtk.Action(name="FileMenu", label="File")
action_group.add_action(action_filemenu)
action = Gtk.Action(name='MenuAction',
label="Menu action",
stock_id=Gtk.STOCK_NEW)
action.connect('activate', self.on_menu_action)
action_group.add_action_with_accel(action, 'N')
def add_toolbar_action(self, action_group):
action = Gtk.Action(name='ToolbarAction',
label="Press me",
stock_id=Gtk.STOCK_MEDIA_STOP)
action.connect('activate', self.on_toolbar_action)
action_group.add_action_with_accel(action, 'X')
def on_menu_action(self, widget):
print 'Menu action'
def on_toolbar_action(self, widget):
print 'Toolbar action'
def create_ui_manager(self):
uimanager = Gtk.UIManager()
uimanager.add_ui_from_string(UI_INFO)
self.add_accel_group(uimanager.get_accel_group())
return uimanager
window = MyWindow()
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()
How can I make pressing X
shortcut invoke the callback?
(The reference for GTK+ 3 say that add_action_with_accel
is deprecated, so there's surely a better way to create the accelerators, but the doc doesn't show the way, and I couldn't find a better tutorial.)