2. Toggle Buttons

Toggle buttons are derived from normal buttons and are very similar, except they will always be in one of two states, alternated by a click. They may be depressed, and when you click again, they will pop back up. Click again, and they will pop back down.

Toggle buttons are the basis for check buttons and radio buttons, as such, many of the calls used for toggle buttons are inherited by radio and check buttons. I will point these out when we come to them.

Creating a new toggle button:

$togglebutton = Gtk2::ToggleButton->new($mnemonic);

$togglebutton = Gtk2::ToggleButton->new_with_label($label);

$togglebutton = Gtk2::ToggleButton->new_with_mnemonic($label);

As you can imagine, these work identically to the normal button widget calls. The first creates a blank toggle button, and the last two, a button with a label widget already packed into it. The plain and _mnemonic() variants additionally parse the label for '_'-prefixed mnemonic characters.

To retrieve the state of the toggle widget, including radio and check buttons, we use a construct as shown in our example below. The signal of interest to us emitted by toggle buttons (the toggle button, check button, and radio button widgets) is the "toggled" signal. To check the state of these buttons, set up a signal handler to catch the toggled signal, and call Gtk2::ToggleButton::get_active() to determine its state. The callback will look something like:

sub toggle_button_callback {
    my $button = shift;
    
    if ($button->get_active) {
        # if control reaches here, the toggle button is down
    } else {
        # if control reaches here, the toggle button is up
    }   
} 

To force the state of a toggle button, and its children, the radio and check buttons, use the Gtk2::ToggleButton::set_active() method. This function can be used to set the state of the toggle button, and its children the radio and check buttons. The function takes only one parameter, a TRUE or FALSE for the state. Default is up, or FALSE.

Note that when you use the Gtk2::ToggleButton::set_active() function, and the state is actually changed, it causes the "clicked" and "toggled" signals to be emitted from the button.

The Gtk2::ToggleButton::get_active() function will return the current state of the button as a boolean TRUE/FALSE value.