0

在我的小型 PyGObject/GTK3 应用程序中,我尝试创建一个由RadioMenuItems 组成的(子)菜单。

我在主窗口中创建如下菜单__init__

menu_item = None
self.menu = Gtk.Menu()
self.menu_items = {}
for i in range(1,5):
   menu_item = Gtk.RadioMenuItem(menu_item)
   menu_item.set_label(str(i))
   self.menu_items[i] = menu_item
   self.menu.append(self.menu_items[i])
   self.menu_items[i].connect("activate",
                        self.on_menu_select,
                        i)
   self.menu_items[i].show()

然后在button_press_event处理程序中使用

def button_press(self, widget, event, data=None):
    for i in range(1,5):
        self.menu_items[i].set_active(False)
    self.menu_items[2].set_active(True)
    self.menu.popup(None, None, None, None,
                            event.button, event.time)

当我第一次打开菜单时,菜单项“2”是唯一选择的。当我然后 - 例如 - 选择菜单项“3”并再次打开菜单时,菜单项 2 和 3 都被选中。我究竟做错了什么?

4

1 回答 1

1

You have to put the radio menu items in a group with each other, or else they won't know to deselect themselves when another one is selected:

self.menu = Gtk.Menu()
self.menu_items = list()
group = []
for i in range(1,5):
    menu_item = Gtk.RadioMenuItem.new_with_label(group, str(i))
    group = menu_item.get_group()
    self.menu_items[i] = menu_item
    self.menu.append(menu_item)
    menu_item.connect("activate", self.on_menu_select, i)
    menu_item.show()

self.menu_items[2].set_active(True)

请注意,此行选择项目编号 2,您不必自己做,因此您的按钮按下处理程序可以简单地是:

def button_press(self, widget, event, data=None):
    self.menu.popup(None, None, None, None,
                    event.button, event.time)
于 2012-04-29T09:38:23.980 回答