Python gtk:如何将列表中的项目插入到组合框中

时间:2014-05-20 10:49:56

标签: python python-2.7 combobox gtk pygtk

我在将项目从现有列表插入到组合框时遇到问题,这是我的代码:

    #retrieving data:
    cursor = self.__db.cursor()        
    cursor.execute("select * from some_table")

    #creating a list:
    row = cursor.fetchone()        
    list = gtk.ListStore(str)
    list.append([row[0]])
    all_rows = cursor.fetchall()
    for row in all_rows:
        i = i + 1
        list.append([row[0]])

    #creating combo-box:
    self.combo_software = gtk.combo_box_entry_new_text()
    for name in list:
        self.combo_software.append_text(name[0])

嗯,它的工作正常,但最后两行完全没有效率。

如何以更快捷的方式插入所有这些项目?

非常感谢

1 个答案:

答案 0 :(得分:3)

您可以直接将组合框绑定到List / TreeModel。要做到这一点,你需要设置一个CellRenderer并绑定它的"文本"属性到模型中的列。通过这样做,模型的更新将自动反映在视图中:

import gtk

model = gtk.ListStore(str)
data = [['test ' + str(i)] for i in range(10)]

for row in data:
    model.append([row[0]])

cell = gtk.CellRendererText()
combo = gtk.ComboBox(model=model)
combo.pack_start(cell)
# Set the "text" attribute of CellRendererText to pull from column 0 of the model
combo.set_attributes(cell, text=0)

w = gtk.Window()
w.add(combo)
w.show_all()

gtk.mainloop()

这也可能有用: http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html

作为旁注,掩盖内置的Python类型可能不是一个好主意,例如" list"因为它可能会在以后的代码中引起奇怪的错误:

list = gtk.ListStore(str)
...
# convert an iterable using the "list" builtin will now break later in code.
another_list = list(some_iterable)
TypeError: 'gtk.ListStore' object is not callable