GTK+2 Programming

GTK+2 Programming

This guide assumes that you know the basics of C programming.


GTK is a cross-platform GUI programming library licensed under the GNU LGPL. There is more information on the GTK+ Project page.
Originally written to develop the GNU Image Manipulation Program (GIMP), GTK is the GIMP ToolKit built on top of GDK (GIMP Drawing Kit) which is basically a wrapper for low-level functions used to access the underlying windowing functions (Xlib for Linux).
GTK+ is written in C, but there are bindings for many other languages. We're gonna use C here!. The API is object-oriented using classes and callback functions, most (if not all) widgets are derived from GObject.
GTK was first released in 1998. GTK+2 has been around since 2002, development ended at Version 2.24 in 2011 with the introduction of GTK+3.
Enuff, let's write some code!

Point & Click

Open your favourite text editor, which I know is Spartan and paste in the code below. Editors such as gedit and pluma use GtkSourceView which does nice formatting for code.

Wherever you see "look this up", refer to the GTK+2 Reference Manual.

Compile it:

	gcc -Wall `pkg-config --cflags --libs gtk+-2.0` -o yeah yeah-src.c
Notice the type-casting macros, like GTK_WINDOW(wdw) and GTK_LABEL(label). These are used because we have created a widget (like GtkLabel) which inherits from another widget (in this case GtkMisc), and in turn from a GtkWidget. The compiler will check any API call using this object to see that it is properly cast to the appropriate type.
You could just as easily type-cast in this manner (GtkWindow*)wdw and (GtkLabel*)label. Im the next example a widget dlg is created in the About function. Within the function, it is cast as GtkWindow, GtkAboutDialog and GtkDialog.