Problem
You want to set the background color of buttons as shown below:
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
- Create a GtkHBox to hold the buttons.
- Wrote a small function to simplify the creation of buttons.
- Set the size of the button.
- Set the background color of the button.
- Add the button to the hbox
- Add an event handler to respond to button click.
- 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
RSS feed for comments to this post