设置组合框的输入(gtk)

时间:2012-02-08 16:26:40

标签: gtk python-3.x

如何在不知道其ID的情况下设置组合框的文本?我有一个名字列表的组合框('杰克','艾米丽','保罗',......)。默认情况下,组合设置为-1,但我希望将其设置为“Paul”。

这是我用tuple(id,fabName)声明和填充组合的代码:

    self.cmbFabricant = builder.get_object("cmbFabricant")
    self.cmbFabricant.set_model(lstStore)
    self.cmbFabricant.set_entry_text_column(1)

现在,我想在名为“Paul”的项目上设置组合框。我以为我可以写:

    self.cmbFabricant.set_active_id('Paul')

我错了。

1 个答案:

答案 0 :(得分:1)

我可能错了,但我认为set_active_id是GTK + 3的新功能,PyGTK是GTK + 2.如果你想使用GTK + 3,你必须切换到PyGObject

但如果你坚持使用PyGTK,你可以通过这样的方式轻松解决它:

import gtk

def set_active_name(combobox, col, name):
    liststore = combobox.get_model()
    for i in xrange(len(liststore)):
        row = liststore[i]
        if row[col] == name:
            combobox.set_active(i)

window = gtk.Window()
window.connect("destroy", gtk.main_quit)

liststore = gtk.ListStore(int, str)
liststore.append([0, 'Jack'])
liststore.append([1, 'Emily'])
liststore.append([2, 'Paul'])

combobox = gtk.ComboBox()
cell = gtk.CellRendererText()
combobox.pack_start(cell)
combobox.add_attribute(cell, 'text', 1)
combobox.set_model(liststore)

set_active_name(combobox, 1, 'Paul')

window.add(combobox)
window.show_all()

gtk.main()

我不确定是否有更优雅/更有效的方法,但这至少有效。