Is it possible to edit menu items in runtime in Python using gtk?

Viewed 323

I am writing simple app in python, I want to write a menu using PyGtk. The problem is that under "Connect" menu item I want to have a list of avaliable devices which changes during program operation. So far my code for creating menu items is as below:

import gtk
import gobject

class Foo(object):
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        gobject.timeout_add(2000, self.AddNewDevice_TEST)   

        table = gtk.Table(2,1,False)
        window.add(table)

        menubar = gtk.MenuBar()

        self.connectMenu = gtk.Menu()
        connectItem = gtk.MenuItem("Connect")
        connectItem.set_submenu(self.connectMenu)

        dev1 = gtk.MenuItem("device1")
        dev1.connect("activate", self.connectToDev)
        self.connectMenu.append(dev1)

        menubar.append(connectItem)

        table.attach(menubar, 0,1,0,1)

        window.show_all()   

    def connectToDev(self, device):
        pass

    def AddNewDevice_TEST(self):
        dev = gtk.MenuItem("device")
        dev.connect("activate", self.connectToDev)
        self.connectMenu.append(dev)


if __name__=='__main__':
    gui = Foo()
    gtk.main()

Problem is that when new device appears in my system or it is disconnected I want to add it or remove it from the list under "Connect". I am able to edit list of devices in menu but after calling gtk.main() I can't make changes any more. Is there any way to do that in runtime?

1 Answers

You can change menu items during runtime in a different thread, e.g. GObject.idle_add(self.connectMenu.remove, dev1) or GObject.idle_add(self.connectMenu.append, dev1). The methods mentioned for GtkMenuShell in the GNOME Developer Documentation might be helpful.

Don't forget to call show() on the MenuItems as mentioned in the answer to this question.

Related