How to create GUI in C programming using GTK Toolkit - GeeksforGeeks

19 Feb, 2020
Many programming languages bolster GUI improvement as one of the centrepieces of its language highlights. C has no such library connected to it like the string library, IO library, etc, that we every now and again use. This weakness opened the skyline for engineers to pick from a wide assortment of GUI library toolbox accessible in C. GTK+ is one of them. It represents GIMP (GNU Image Manipulation Program) Toolkit and can be utilized to program current GUI interfaces.
The beneficial thing about GTK+ is that it is steady, developed, and its starting point can be followed back to the past times of X Windows that structure the centre GUI arrangement of Linux today. GTK is completely written in C and the GTK+ programming that we regularly use in Linux is additionally written in C. The work area administrators, for example, GNOME and XFCE, likewise are manufactured utilizing GTK.
A GTK+ application isn’t limited to the Linux stage no one but; it very well may be ported to non-UNIX/Linux stages also.
Here, we will cling to the fundamental type of GTK+, which is its C avatar on the Linux stage. The official webpage to download GTK+ is https://www.gtk.org. The site contains API documentation, instructional exercises, and other Gnome libraries that are frequently utilized alongside GTK. Truth be told, GTK is based over libraries, for example,
ATK: This library provides help to create accessibility tools such as sticky keys, screen readers, etc.
Glib: It is a universally useful utility library that offers help for threads, dynamic loading, event loops, low-level data structures, etc.
GObject: This library gives full-featured object-oriented help in C, without utilizing C++. This library encourages the language binding made for different languages to give you simple access to C APIs.
GdkPixBuf: This library gives picture control capacities.
GDK (GIMP Drawing Toolkit): This is the designs library that gives low-level drawing capacities over Xlib.
Pango: This library helps in content and design rendering
Xlib: This library provides low-level graphics support for Linux system
When composing code with GTK, we regularly locate that a significant number of the primitive data types are prefixed with ‘g‘ as in
gint,
gchar,
gshort,
gpointer,
etc.
These data types guarantee that the code can be recompiled on any platform without rolling out any improvements. These data types are characterized in these libraries to help in making it platform-independent.
GUI programming inherent object-oriented in it which is the main issue. In this, a procedural worldview doesn’t fit consummately in this scheme. Thus, regardless of GTK being written in C, it gives object-oriented help through GObject. Note that this item arranged help has nothing to do with C++. C++ has its own GTK library, called gtkmm. GObject encourages a portion of the object-oriented principles, similar to polymorphism and inheritance with the assistance of macros. The following diagram illustrates the hierarchical relation.
GtkWindow inherits GtkBin, which itself is a child of GtkContainer; in this manner, an object of GtkWindow can call the function defined in GtkBin or GtkContainer. This is an example of object-oriented implementation in C by GTK.
Let us comprehend a couple of things from our first GTK code in C.
To start with, we incorporate the header file. This incorporates all the file one needs to make a GUI, including the Glib library.#include <gtk/gtk.h>
#include <gtk/gtk.h>
Presently, we declare a pointer to GtkWidget, which is only a window for our situation. What’s more, another GtkWidget pointer will be the button. Review that GtkWidget is a top-level storage type for widgets in the hierarchy.GtkWidget *window;
GtkWidget *button;
GtkWidget *window;
GtkWidget *button;
Next, we invoke gtk_init function to initialize the GTK+ libraries by passing the command line parameters of the main function.gtk_init(&argc, &argv);
gtk_init(&argc, &argv);
All GTK+ applications are instated as such; it is an “absolute necessity” statement. It parses the command arguments line and returns back to the application. Accordingly, these parameters might be utilized to alter the run time conduct of the application.
Now, we create the window and the button.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
button = gtk_button_new_with_label
   ("Click Me!");
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
button = gtk_button_new_with_label
   ("Click Me!");
The window type value GTK_WINDOW_TOPLEVEL implies that the window made will be a standard framed window. Other sort values might be GTK_WINDOW_POPUP, which implies a frameless dialogue window will be made.
When we make a window, it must be closable with the goal that the client should at any rate ready to close the application because of the client hitting the upper right close the window. This implies the window must have the option to react to an event (close event).
Like all windowing system, GTK+ additionally executes events and event handlers. Since the code that transmits the signal is interior to a specific object, we have to compose an interfacing callback function.
The organization of a regular callback function is:void my_callback_function(GtkWidget *widget, gpointer data);
void my_callback_function(GtkWidget *widget, gpointer data);
The primary parameter represents the widget that produces the signal and the subsequent parameter is a void pointer that might be utilized for any reason. Along these lines, the callback function to deal with the close events of our window will be as per the following:void destroy( GtkWidget *widget, gpointer   data )
{
   gtk_main_quit ();
}

void destroy( GtkWidget *widget, gpointer   data )
{
   gtk_main_quit ();
}

The function gtk_main_quit() shuts the application. Presently, we should interface the window object with the callback function.g_signal_connect (window, "destroy",
                  G_CALLBACK (destroy),
                  NULL);
g_signal_connect (window, "destroy",
                  G_CALLBACK (destroy),
                  NULL);
Likewise, we make the callback function to deal with the button event and associate it with the button widget.void greet( GtkWidget *widget, gpointer data )
{
   g_print ("Welcome to GTK\n");
   g_print ("%s clicked %d times\n",
      (char*)data, ++counter);
}
g_signal_connect (GTK_OBJECT(button), "clicked",
   G_CALLBACK (greet), "button");
void greet( GtkWidget *widget, gpointer data )
{
   g_print ("Welcome to GTK\n");
   g_print ("%s clicked %d times\n",
      (char*)data, ++counter);
}
g_signal_connect (GTK_OBJECT(button), "clicked",
   G_CALLBACK (greet), "button");
Since the button widget is contained inside the window, we should explicitly add it to the container.gtk_container_add (GTK_CONTAINER (window), button);
gtk_container_add (GTK_CONTAINER (window), button);
Also, at long last, we show the widgets made in memory with the gtk_widget_show_all() function that takes a reference to the window we have made.
Finally, the gtk_main() function is summoned to begin the interactive procedure.gtk_widget_show_all(window);
gtk_main();
gtk_widget_show_all(window);
gtk_main();
This is a key function on the grounds that ordinarily a C program ends in the wake of executing the last statement. Here, it passes the control of the program to GTK+ and stays away for the indefinite future until the gtk_main_quit event is activated by the client tapping the close button for our situation.
Below is the implementation of the above steps:
#include <gtk/gtk.h>  static int counter = 0;  void greet(GtkWidget* widget, gpointer data){    // printf equivalent in GTK+    g_print("Welcome to GTK\n");    g_print("%s clicked %d times\n",            (char*)data, ++counter);}  void destroy(GtkWidget* widget, gpointer data){    gtk_main_quit();}  int main(int argc, char* argv[]){      GtkWidget* window;    GtkWidget* button;    gtk_init(&argc, &argv);      window = gtk_window_new(GTK_WINDOW_TOPLEVEL);      g_signal_connect(window, "destroy",                     G_CALLBACK(destroy), NULL);    /* Let's set the border width of the window to 20.    * You may play with the value and see the    * difference. */    gtk_container_set_border_width(GTK_CONTAINER(window), 20);      button = gtk_button_new_with_label("Click Me!");      g_signal_connect(GTK_OBJECT(button),                     "clicked", G_CALLBACK(greet),                     "button");      gtk_container_add(GTK_CONTAINER(window), button);      gtk_widget_show_all(window);      gtk_main();      return 0;}
For Compiling write the following command (with GCC in Linux)gcc main.c -o p1
   `pkg-config --cflags --libs gtk+-2.0`
gcc main.c -o p1
   `pkg-config --cflags --libs gtk+-2.0`
To run it write the following command./p1
./p1
ConclusionGTK+ has all the GUI segments one needs to make an expert looking interface. The essential thought of GUI occasion driven programming with GTK+ isn’t very different from the one appeared in the model. Include a couple of more parts, utilize various sorts of compartments, play with designs, and obviously always remember to counsel the GTK+ documentation. Proficient developers frequently utilized RAD tools, for example, Glade to plan the GUI interface rapidly. Be that as it may, in the first place, have a go at composing the code without any preparation to get a vibe of what goes where and how it is really done. It will compensate you later.
AkhilKG
c-graphics
Picked
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
UDP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
How to dynamically allocate a 2D array in C?
Unordered Sets in C++ Standard Template Library