Part 9e

ComboBoxes

Populating the ComboBox

Populating the content of a ComboBox based on a users choice is a powerful tool for applications. I’ve seen many applications that have a ComboBox with way too many choices to pick from when using this method would simplify the UI (User Interface) greatly.

First we will add the code that creates the liststore. I won’t go into great detail as this is covered in Gtk ComboBox. Add the following to the init of main class.

Create the Liststore
class main:
  def __init__(self):
    # create an instance of the Builder
    self.builder = gtk.Builder()
    self.builder.add_from_file('lib/main.glade')
    self.builder.connect_signals(self)

    # create the cell renderer
    self.cell = gtk.CellRendererText()

    # create the liststores for our combobox
    self.furry_list = gtk.ListStore(int, str)
    self.furry_list.append([0, 'None'])
    self.furry_list.append([1, 'Rabbit'])
    self.furry_list.append([2, 'Cat'])
    self.furry_list.append([3, 'Hamster'])

    self.slimy_list = gtk.ListStore(int, str)
    self.slimy_list.append([0, 'None'])
    self.slimy_list.append([1, 'Snake'])
    self.slimy_list.append([2, 'Fish'])
    self.slimy_list.append([3, 'Slug'])

    #populate the default choice into the combobox
    self.cb1 = self.builder.get_object('combobox1')
    self.cb1.set_model(self.furry_list)
    self.cb1.pack_start(self.cell, True)
    self.cb1.add_attribute(self.cell, 'text', 1)
    self.cb1.set_active(0)

    # setup the main window
    self.window = self.builder.get_object("window1")
    self.window.set_title("ComboBoxes")
    self.window.show_all()

Next we need to change the toggled modules to change the contents of the combo box. The main thing is to clear the combo box before trying to add a new liststore to it.

  def on_radiobutton1_toggled(self, widget):
    if widget.get_active():
      self.cb1.clear()
      self.cb1.set_model(self.furry_list)
      self.cb1.pack_start(self.cell, True)
      self.cb1.add_attribute(self.cell, 'text', 1)
      self.cb1.set_active(0)

  def on_radiobutton2_toggled(self, widget):
    if widget.get_active():
      self.cb1.clear()
      self.cb1.set_model(self.slimy_list)
      self.cb1.pack_start(self.cell, True)
      self.cb1.add_attribute(self.cell, 'text', 1)
      self.cb1.set_active(0)

Now when you run main.py and select a radio button it will populate the combobox with the liststore you chose with the radio button. This makes the UI much less crowded and easier to navigate.

images/glade-09-04.png