Snippet. Vala. Create a Button with Image

Here is how to create a button with custom image displayed on the left of the button and label on the right:

  • Create a standard horizontal layout with GtkHBox.
  • Create a new image with GtkImage, pointing to the image file.
  • Pack the image in the hbox.
  • Create a new label with GtkLabel and pack it inside the hbox too.
  • Create a standard GtkButton.
  • Add the GtkHBox into the GtkButton
// 1. Create the horizontal layout
Gtk.HBox box = new Gtk.HBox(false, 0);
    box.set_border_width(2);
    
// 2. Create the image with the custom file
Gtk.Image image = new Gtk.Image();
    image.set_from_file("run.png");
// 3. Create a label for the button
Gtk.Label label = new Gtk.Label("Click me");
    label.set_markup("<span foreground=\"red\" size=\"32000\"><b>Click me</b></span>");

// 4. Pack the image and label into the box
box.pack_start(image, false, false, 20);
box.pack_start(label, false, false, 3);
image.show();
label.show();

// 5. Create the button and add the layout
Gtk.Button button = new Gtk.Button();
button.add(box);

// 6. Connect the click signal
button.clicked.connect(button_clicked);

Result


Updated on: 01 Dec 2021