python GTK : How to insert items from list to combobox

标签 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])

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

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

非常感谢

最佳答案

您可以将组合框直接绑定(bind)到 List/TreeModel。为此,您需要设置 CellRenderer 并将其“文本”属性绑定(bind)到模型中的列。通过这样做,对模型的更新会自动反射(reflect)在 View 中:

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

关于 python GTK : How to insert items from list to combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757738/

相关文章:

Python 记录器不遵守 setLevel?

python - 如何切换窗口停留在顶部提示

当项目源更改时,WPF ComboBox 会重置所选项目

.net - 如何使用来自数据库的绑定(bind)将选项 "All"添加到 WPF 中的组合框

python - 将直方图从 Python 导出到 Excel

python - Python 中的多处理(HoG 功能) - 返回空数组

Python.Net 无法导入 dll

python - 每次我运行 "jupyter notebook"时,为什么我总是在 mac os 上得到这个?

python - MySQL 连接对象的属性错误

java - 使用 Java 获取 WebDriver 中组合框选定选项的标签之间的文本