Creating a GUI in C using the GTK Toolkit
GTK (GIMP Toolkit) is a popular open-source library used for creating graphical user interfaces (GUIs) in C. It is cross-platform and used in applications like GIMP and GNOME.
1. Installing GTK
Before coding, you need to install GTK on your system.
For Linux (Ubuntu/Debian)
sudo apt update
sudo apt install libgtk-3-dev
For Windows
Download and install GTK from MSYS2.
Install GTK dependencies:
pacman -S mingw-w64-x86_64-gtk3
Use pkg-config to compile GTK applications.
2. Writing a Simple GTK Application
Here’s a basic C program that creates a window with a button.
Code: main.c
#include
// Callback function for button click
void on_button_clicked(GtkWidget *widget, gpointer data) {
g_print(“Button clicked!\n”);
}
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *button;
GtkWidget *box;
// Initialize GTK
gtk_init(&argc, &argv);
// Create a window
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), “GTK GUI in C”);
gtk_window_set_default_size(GTK_WINDOW(window), 400, 200);
// Connect the “destroy” event to close the window
g_signal_connect(window, “destroy”, G_CALLBACK(gtk_main_quit), NULL);
// Create a vertical box layout
box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
gtk_container_add(GTK_CONTAINER(window), box);
// Create a button
button = gtk_button_new_with_label(“Click Me”);
g_signal_connect(button, “clicked”, G_CALLBACK(on_button_clicked), NULL);
// Add button to the box
gtk_box_pack_start(GTK_BOX(box), button, TRUE, TRUE, 0);
// Show all widgets
gtk_widget_show_all(window);
// Start the GTK main loop
gtk_main();
return 0;
}
3. Compiling and Running the GTK Program
Use pkg-config to compile the program.
For Linux/macOS
gcc main.c -o my_gui $(pkg-config –cflags –libs gtk+-3.0)
./my_gui
For Windows (MSYS2)
gcc main.c -o my_gui.exe $(pkg-config –cflags –libs gtk+-3.0)
./my_gui.exe
4. Explanation of Code
gtk_init(&argc, &argv); → Initializes GTK.
gtk_window_new(GTK_WINDOW_TOPLEVEL); → Creates a window.
gtk_button_new_with_label(“Click Me”); → Creates a button with text.
g_signal_connect(button, “clicked”, G_CALLBACK(on_button_clicked), NULL); → Connects a function to handle button clicks.
gtk_main(); → Starts the GTK event loop.
5. Adding More Widgets
You can enhance the GUI by adding labels, text inputs, and images.
Example: Adding a Label and Entry Field
GtkWidget *label = gtk_label_new(“Enter your name:”);
GtkWidget *entry = gtk_entry_new();
gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(box), entry, TRUE, TRUE, 0);
6. Conclusion
GTK provides a simple way to create cross-platform GUI applications in C.
Leave a comment