簡體   English   中英

設置組合框(gtk)的條目

[英]set up the entry of a combobox (gtk)

如何在不知道組合框ID的情況下設置組合框的文本? 我有一個組合框,上面有一個名稱列表('Jack','Emily','Paul',...)。 默認情況下,組合設置為-1,但我希望將其設置為“ Paul”。

這是我的代碼,用元組(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')

我錯了。

我可能錯了,但是我認為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()

我不確定是否有更優雅/有效的方法,但這至少有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM