Programatically add new menu items to menu item PyGObject?

萝らか妹 提交于 2019-12-24 03:53:26

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/21582745/programatically-add-new-menu-items-to-menu-item-pygobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!