391. How to create a flashing button - Part 1?

Problem

You would like to create a flashing background color as shown below. The 'Click Me' button will keep flashing until the user clicks on the button.

How to create a flashing button - 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   
31   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
42   
43   
44   
45   
46   
48   
49   
50   
51   
52   
<?php
$window = new GtkWindow();
$window->connect_simple('destroy', array( 'Gtk', 'main_quit'));
$window->set_size_request(400,150);

$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Create a Flashing Button - 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, 60);
$vbox->pack_start($title, 0, 0);

$vbox->pack_start($hbox=new GtkHBox(), 0, 0);
$button = create_button($hbox, 'Click Me!', '#FFCC66');
$timeout_handle = Gtk::timeout_add(500, 'flash', $button, '#FFCC66'); // note 1

$window->realize();
$org_bg = $window->get_style()->bg[Gtk::STATE_NORMAL]; // note 2

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

function create_button($hbox, $button_label, $bg_color) {
    $button = new GtkButton($button_label);
    $button->set_size_request(80, 32);
    $button->modify_bg(Gtk::STATE_NORMAL,
        GdkColor::parse($bg_color));
    $hbox->pack_start($button, 1, 0);
    $button->connect('clicked', "on_button", $button_label);
    return $button;
}

function on_button($button, $button_label) {
    echo "You have clicked: $button_label!\n";
    global $timeout_handle;
    Gtk::timeout_remove($timeout_handle); // note 4
}

function flash($button, $bgcolor_str) {
    static $i=1;
    global $org_bg;
    $bgcolor = GdkColor::parse($bgcolor_str);
    $bg = ($i==1) ? $org_bg : $bgcolor; // note 3
    $button->modify_bg(Gtk::STATE_NORMAL, $bg); // note 3
    $i = ($i==1) ? 0 : 1;
    return true;
}

?>

Output

As shown above.
 

Explanation

The above code is based on How to set the background color of GtkButton?

What's new here:

  1. Call the function flash() once every 500ms (i.e. half a second).
  2. Get the default gray color of the button.
  3. Alternate the background color of the button to create the flashing effect.
  4. Stops the flashing!

Related Links

Add comment


Security code
Refresh