Cody Dostal
Cody Dostal

Reputation: 311

Programatically add new menu items to menu item PyGObject?

I had this set up in wxPython, but now I'm rewriting it for GTK3/PyGObject, and I'm kind of lost here. Basically, my code scans through a directory, and adds the names of files to a menu item. I can't get it to work in PyGObject. Here is the current code:

# Populate profiles menu
        profileMenu = self.builder.get_object("profilesMenu")
        profiles = os.listdir("/etc/netctl/")
        # Iterate through profiles directory, and add to "Profiles" Menu #
        for i in profiles:
            if os.path.isfile("/etc/netctl/" + i):
                profile = profileMenu.set_menu_item(i)

I've tried various profileMenu.* ideas. The first one I tried was set_submenu, which returns the following error:

[cody@cody-arch NetGUI]$ sudo python main.py 
Traceback (most recent call last):
  File "main.py", line 466, in <module>
    netgui()
  File "main.py", line 70, in __init__
    self.InitUI()
  File "main.py", line 140, in InitUI
    profile = profileMenu.set_submenu(i)   
TypeError: argument submenu: Expected Gtk.Widget, but got str

The current one just says set_menu_item doesn't exist, so obviously that won't work. What should I try to do to fix this? I'm completely lost. I know why set_submenu doesn't work, I don't know how to fix it. How would I make a filename a Gtk.Widget?

Upvotes: 2

Views: 1088

Answers (1)

Havok
Havok

Reputation: 5882

What you're looking for is append(). Also, the common hierarchy is:

  • GtkMenuBar
    • GtkMenuItem
      • GtkMenu
        • GtkMenuItem
        • GtkImageMenuItem
        • GtkCheckMenuItem
        • GtkRadioMenuItem
        • GtkSeparatorMenuItem

You can find a full example here:

https://gist.github.com/carlos-jenkins/8851942

The relevant part of the code is:

    content = [
        'Path to file 1',
        'Path to file 2',
        'Path to file 3',
        'Path to file 4',
    ]

    # Create menu
    menu = Gtk.MenuItem(label='My Menu {}'.format(num))
    menu.set_submenu(Gtk.Menu())

    for p in content:
        menu.get_submenu().append(Gtk.MenuItem(label=p))

    self.menubar.append(menu)
    menu.show_all()

Upvotes: 2

Related Questions