gtk组合框:添加带有两个字段的项目

0 投票
1 回答
835 浏览
提问于 2025-04-18 07:18

我想在组合框(combo-box)这个小工具里添加一些项目,这样用户在选择一个项目的时候,可以看到一个字段,而程序则能看到两个字段的信息。

这是我的代码:

slist = gtk.ListStore(str, str)
slist.append(['item_name1', 'item_id1'])
slist.append(['item_name2', 'item_id2'])
slist.append(['item_name3', 'item_id3'])

self.combobox = gtk.ComboBox(model=slist)

cell = gtk.CellRendererText()
self.combobox.pack_start(cell)
self.combobox.add_attribute(cell, 'text', 1)
self.combobox.set_model(slist)

谢谢

1 个回答

2

这个例子已经设置好了一个模型,里面有两列数据,但视图只显示了一列。如果你想从某个选择中获取两列数据,可以使用“get_active_iter()”这个方法,并结合一个“changed”信号,这样就能提取出整行数据:

def on_selection_changed(combo):
    itr = combo.get_active_iter()
    print(slist.get_value(itr, 0), slist.get_value(itr, 1))

combobox.connect('changed', on_selection_changed)

另请参见:http://pygtk.org/docs/pygtk/class-gtkcombobox.html#method-gtkcombobox--get-active-iter

撰写回答