384. How to setup and process toggle buttons - Part 1?

Problem

You want to setup toggle buttons and find out the status of each toggle button as shown below:

How to setup and process toggle buttons - Part 1?


Solution


Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
20   
21   
22   
23   
24   
25   
26   
27   
28   
29   
30   
38   
39   
40   
41   
42   
43   
44   
45   
46   
47   
48   
49   
50   
51   
52   
53   
54   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 150);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Setup and Process Toggle Buttons - Part 1");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0, 0);
$vbox->pack_start(new GtkLabel(), 0);

$vbox->pack_start($hbox = new GtkHBox(), 0);
$button1 = setup_button($hbox, 'button 1');
$button2 = setup_button($hbox, 'button 2');
$button3 = setup_button($hbox, 'button 3');

$vbox->pack_start($status = new GtkLabel());

$window->show_all();
Gtk::main();

function setup_button($container, $button_label) {
    $button = new GtkToggleButton($button_label); // note 1
    $container->pack_start($button, 0);
    $container->pack_start(new GtkLabel(' '), 0); // add a small gap
    $button->modify_bg(Gtk::STATE_PRELIGHT, 
        GdkColor::parse("#99FFB3"));
    $button->connect('clicked', 'on_click');
    return $button;
}

function on_click($button) {
    global $status, $button1, $button2, $button3;
    print "You have clicked: ".$button->get_label()."\n";
    $status1 = $button1->get_active()? 'on' : 'off'; // note 2
    $status2 = $button2->get_active()? 'on' : 'off'; 
    $status3 = $button3->get_active()? 'on' : 'off'; 
    $status->set_text( // note 3
        "button 1: $status1\n".
        "button 2: $status2\n".
        "button 3: $status3");
}

?>

Output

As shown above.

 

Explanation

  1. Create the toggle button.
  2. Get the status of each toggle button.
  3. Display the status of the three toggle buttons.

Note

You might want to compare this with theat of How to setup and process checkboxes? The two are actually very similar.

Related Links

Add comment


Security code
Refresh