[pygtk] Dynamic Menus

Jeremy S dumbmatter at gmail.com
Thu Jul 3 07:31:55 WST 2008


I'm building an application with PyGTK and Glade.  I would like to be
able to dynamically change of the menus in by menubar in my Python
code.  So my idea was to create a stub menuitem in a menubar in Glade
and then add a menu to it in my program, but I am having trouble doing
it.  Also, if you think there is a much better way to do this than
what I am trying, please tell me because I'm new to GTK.

The problem is that I can't get the menuitem object, only the action
object.  If it returned the menuitem I could work with that I think,
but I'm not sure what to do with an action object.

Here is some simple code.  I want it to add a menuitem to the menu,
but it doesn't work.

test_menu.py:
------------------------
import gtk

builder = gtk.Builder()
builder.add_from_file('test_menu.xml')
window = builder.get_object('window')
menubar = builder.get_object('menubar')
action_menuitem_file = builder.get_object('menuitem')
print type(action_menuitem_file)

action_menuitem_quit = gtk.Action('Quit', 'Quit', 'Quit the program',
gtk.STOCK_QUIT)
menuitem_file = action_menuitem_file.create_menu_item()
menu_file = gtk.Menu()
menuitem_file.set_submenu(menu_file)
menuitem_quit = action_menuitem_quit.create_menu_item()
menu_file.append(menuitem_quit)

window.show()
gtk.main()

test_menu.xml:
------------------------
<?xml version="1.0"?>
<!--Generated with glade3 3.4.5 on Wed Jul  2 18:57:27 2008 -->
<interface>
  <object class="GtkUIManager" id="uimanager1">
    <child>
      <object class="GtkActionGroup" id="actiongroup1">
        <child>
          <object class="GtkAction" id="menuitem">
            <property name="name">menuitem</property>
            <property name="label" translatable="yes">_File</property>
          </object>
        </child>
      </object>
    </child>
    <ui>
      <menubar name="menubar">
        <menuitem action="menuitem"/>
      </menubar>
    </ui>
  </object>
  <object class="GtkWindow" id="window">
    <child>
      <object class="GtkMenuBar" constructor="uimanager1" id="menubar">
        <property name="visible">True</property>
      </object>
    </child>
  </object>
</interface>


More information about the pygtk mailing list