16.5. Expander Widgets

The Expander widget is a fairly simple container widget that can reveal or hide its child widget by clicking on a triangle similar to the triangle in a TreeView. A new Expander is created using the constructor:

  expander = gtk.Expander(label=None)

where label is a string to be used as the expander label. If label is None or not specified, no label is created. Alternatively, you can use the function:

  expander = gtk.expander_new_with_mnemonic(label=None)

that sets the character in label preceded by an underscore as a mnemonic keyboard accelerator.

The Expander widget uses the Container API to add and remove its child widget:



The child widget can be retrieved using the Bin "child" attribute or the get_child() method.

The setting that controls the interpretation of label underscores can be retrieved and changed using the methods:

  use_underline = expander.get_use_underline()


If you want to use Pango markup (see the Pango Markup reference for more detail) in the label string, use the following methods to set and retrieve the setting of the "use-markup" property:


  use_markup = expander.get_use_markup()

Finally, you can use any widget as the label widget using the following method:


This allows you, for example, to use an HBox packed with an Image and a Label as the Expander label.

The state of the Expander can be retrieved and set using the methods:

  expanded = expander.get_expanded()


If expanded is TRUE the child widget is revealed.

In most cases the Expander automatically does exactly what you want when revealing and hiding the child widget. In some cases your application might want to create a child widget at expansion time. The "notify::expanded" signal can be used to track changes in the state of the expander triangle. The signal handler can then create or change the child widget as needed.

The example program expander.py demonstrates the use of the Expander. Figure 16.11, “Expander Widget” illustrates the program in operation:

Figure 16.11. Expander Widget

Expander Widget

The program creates a Label containing the current time and shows it when the expander is expanded.