FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 16.8 | Next Entry >>

16.8. How do I populate a ComboBox or ComboBoxEntry with strings?

For glade users, you can create a simple model for your ComboBox* using

  store = gtk.ListStore(gobject.TYPE_STRING)
  store.append (["testing1"])
  store.append (["testing2"])
  store.append (["testing3"])
  store.append (["testing4"])
For a ComboBoxEntry, it's then a matter of assigning the model to the combo and specifying the text column:

  combo = tree.get_widget("comboboxentry1")
  combo.set_model(store)
  combo.set_text_column(0)
For a ComboBox, pack a renderer into it, specifying the text cell:

  combo = tree.get_widget("combobox1")
  combo.set_model(store)
  cell = gtk.CellRendererText()
  combo.pack_start(cell, True)
  combo.add_attribute(cell, 'text',0)
Thomas Hinkle offers a convenience function that does all this for you:

  def set_model_from_list (cb, items):
    """Setup a ComboBox or ComboBoxEntry based on a list of strings."""           
    model = gtk.ListStore(str)
    for i in items:
        model.append([i])
    cb.set_model(model)
    if type(cb) == gtk.ComboBoxEntry:
        cb.set_text_column(0)
    elif type(cb) == gtk.ComboBox:
        cell = gtk.CellRendererText()
        cb.pack_start(cell, True)
        cb.add_attribute(cell, 'text', 0)
If you are not using glade, it's easier to use the gtk.combo_box_new_text() function with the append_text(), prepend_text(), insert_text() and remove_text() methods as explained here:

[www.pygtk.org] [www.pygtk.org]

(John Finlay, Thomas Hinkle)

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org