023. How to set the background color of GtkButton?

Problem

You want to set the background color of buttons as shown below:

How to set the background color of GtkButton?


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   
<?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("Set Background Color of Button");
$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); // note 1
create_button($hbox, 'Orange', "#FFCC66"); // note 2
create_button($hbox, 'Green', '#CCFF99');
create_button($hbox, 'Blue', '#CCFFFF');

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

function on_button($button, $button_label) {  // note 7
    echo "You have clicked: $button_label!\n";
}

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

Output

As shown above.
 

Explanation

  1. Create a GtkHBox to hold the buttons.
  2. Wrote a small function to simplify the creation of buttons.
  3. Set the size of the button.
  4. Set the background color of the button.
  5. Add the button to the hbox
  6. Add an event handler to respond to button click.
  7. This is the callback function that is called when the user clicks the button.

Notes

Setting the background color of a GtkButton is relatively easier than setting the background color of a GtkLabel.

To set the background of a GtkLabel, please refer to How to set the background color of GtkLabel?

Comments   

+1 # Alexander Niedernhoefer 2014-07-30 03:42
Tried this with Windows 7 64-bit, no colored Buttons ... took the code 1:1 from the above example.
Reply | Reply with quote | Quote

Add comment


Security code
Refresh