392. How to create a flashing button - Part 2?

Problem

We have created a flashing background color in Part 1.

However, if you have run that sample code, you will notice that the button stops flashing when your mouse is over the button.

We will fix this is this Part 2 so that the button will continue to flash even when the mouse is over it as shown below.

How to create a flashing button - Part 2?


Solution

  • The button stops flashing because we did not set the PRELIGHT state of the button in Part 1.
  • To fix this, we just need to add one more modify_bg for the PRELIGHT state.

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   
47   
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 2");
$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');

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

$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;
    if ($timeout_handle!=null) Gtk::timeout_remove($timeout_handle);
}

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

?>

Output

As shown above.
 

Explanation

The above code is based on How to create a flashing button - Part 1?

What's new here:

  1. Set the background color of the NORMAL state.
  2. Set the background color of the PRELIGHT state.

Related Links

Add comment


Security code
Refresh