GTK+ and Glade3 GUI Programming Tutorial - Part 3

Writing a Basic Program to Implement the Glade File

In this part of the GTK+ and Glade3 GUI Programming Tutorial series, I will show you a very basic program that will parse the Glade file we created in Part 1 and display the main window for our GTK+ text editor. In this part of the tutorial, I will be discussing the GTK+ concepts first and then show the code in both Python and C (in different colors). If you have chosen to work in one language or the other, you can opt to skip over the code explanation for the language you are not going to use.

Contents

  1. Part 1 - Designing a User Interface Using Glade 3
    1. Quick Overview of GTK+ Concepts
    2. Introduction to Glade3
    3. Getting Familiar with the Glade Interface
    4. Manipulating Widget Properties
    5. Specifying Callback Functions for Signals
    6. Adding Widgets to the GtkWindow
    7. How Packing Effects the Layout
    8. Editing the Menu (or Toolbar)
    9. Final Touches to the Main Window
    10. Getting Additional Help Using Glade
    11. What Next?
  2. Part 2 - Choosing a Programming Language for GTK+ Development
    1. Which is the BEST Language?
    2. Language Choice Considerations
    3. A Look at Python vs. C
    4. What Next?
  3. Part 3 - Writing a Basic Program to Implement the Glade File
    1. Setting Up Your Development Environment
    2. GtkBuilder and LibGlade
    3. The Minimal Application
    4. Compiling and Running the Application
    5. Stepping Through the Code
    6. What's Next?

Setting Up Your Development Environment 

To work with GTK+ and complete this step of the tutorial you will need a text editor, a terminal window, the GTK+ development libraries, and optionally Devhelp, the developer's help reference. If you're new to the Linux world, welcome to lots of options. There isn't one particular editor or IDE that is the "standard". Most developers actually work with their favorite text editor and a terminal window. Although there are some "full featured" IDEs out there, you may want to stick with a plain text editor and terminal at this point so as not to be overwhelmed or tripped up by features and automated tasks the IDE might perform.

I do my work using Gedit, the default GNOME text editor. There is a plugins package available for Gedit which contains a terminal plugin and I have written Gedit Symbol Browser Plugin which allows you to quickly jump to functions in your source code. Below are Gedit screenshots from my system while working on this tutorial (click to see full-size).

GTK+ Programming in C
Working in C

GTK+ Programming in Python
Working in Python

The development libraries you will need depend both on your distribution and whether you want to work in Python or C. Although the process can vary greatly depending on your platform and distribution, I can give you the information you need to get started. If you have problems installing any of the packages you need, post your problem or question at the GTK+ Forums or a forum for your distribution.

When it comes to development libraries with Linux, you can often get all the packages you need using your distributions package manager to resolve dependencies. For example, on Ubuntu you can likely just issue the command: 'sudo aptitude install libgtk-2.0-dev'. This command will install the GTK+ development package, it's dependencies, their dependencies, and so on.

It's important to install the "development packages". These are suffixed with "-dev" in Ubuntu/Debian and "-devel" in Redhat/Fedora. The development packages include header files and other includes that allow you to build applications which use a particular library. Just remember, "package" allows you to run applications using that library where "package-dev" or "package-devel" allows you to write applications using that library.

Another prefix you will see on packages is "-doc" such as "libgtk2.0-doc". This will be the documentation for that library and once installed will allow you to browse the documentation using Devhelp: the GNOME developer's help browser.

If you're programming with C you should install the following packages with their dependencies: build-essential, libgtk2.0-dev, libgtk2.0-doc, libglib2.0-doc, devhelp (package names may vary depending on distribution, these are for Ubuntu).

If you're programming with Python you should install the following packages with their dependencies: python2.5-dev python2.5-doc, python2.5-gtk2, python-gtk2-doc, python-gobject-doc, devhelp (package names may vary depending on distribution, these are for Ubuntu).

GtkBuilder and LibGlade 

If you recall, the file we created with Glade in part 1 of this tutorial series (tutorial.glade) was an XML file describing our GUI. The actual GUI will be built by our program. Therefore, the program will have to open and parse the XML file and create instances of the widgets described within. There is already a library written to perform this task--2 libraries in fact.

LibGlade was originally the library used to parse the glade file and create the widgets described within. At the time of writing, this will still be the more commonplace method used in other tutorials and books. However, GTK+ 2.12 included an object called GtkBuilder which is essentially the same thing and is built right in to GTK+. As this is intended to eventually replace Libglade, we will be using GtkBuilder in this tutorial. However, as you learn and look at code elsewhere on the internet, keep in mind that anywhere you see LibGlade being used, GtkBuilder can be used instead.

Since (at the time of writing) GtkBuilder is relatively new, Glade does not yet support saving in the GtkBuilder format. The GtkBuilder format is still an XML file, but with a slightly different schema. That means that in order to use GtkBuilder on a glade file, we must first convert it to the GtkBuilder format. GTK+ 2.12 provides a conversion script for this process, and will already be installed on your system at this point.

You can read some of the common questions I get about all this Libglade/GtkBuilder stuff at Libglade to GtkBuilder F.A.Q..

So we now convert the glade XML file tutorial.glade to the GtkBuilder XML file tutorial.xml with the following command:

gtk-builder-convert tutorial.glade tutorial.xml

The file 'tutorial.xml' is the file we will actually parse in our program, however, we still need tutorial.glade when we want to make changes using Glade. This is only necessary until Glade supports the GtkBuilder format in a later version (They are aiming to have this ready by Glade 3.6 which you can follow along Bug #490678).

The Minimal Application 

We're finally ready to write some code! Let's just recap what we've done so far.

  1. Using Glade, we created tutorial.glade which describes our user interface.
  2. We've selected which language we will use to write our program; Python, C, or both.
  3. We have a text editor and a terminal window available.
  4. We have installed the development libraries we need to program GTK+ applications.
  5. Using gtk-builder-convert, we converted tutorial.glade to tutorial.xml for use with GtkBuilder.

Now, before we start digging in to all the details of what each line of code does, we are going to write a minimal application just to ensure everything works and get acquainted with the development process. So, open up your text editor and type in the following...

If you're programming in C

#include <gtk/gtk.h>

void 
on_window_destroy (GtkObject *object, gpointer user_data)
{
        gtk_main_quit();
}

int
main (int argc, char *argv[])
{
        GtkBuilder              *builder;
        GtkWidget               *window;
        
        gtk_init (&argc, &argv);
        
        builder = gtk_builder_new ();
        gtk_builder_add_from_file (builder, "tutorial.xml", NULL);

        window = GTK_WIDGET (gtk_builder_get_object (builder, "window"));
        gtk_builder_connect_signals (builder, NULL);          
        g_object_unref (G_OBJECT (builder));
        
        gtk_widget_show (window);       
        gtk_main ();
        
        return 0;
}

Save this file as 'main.c' in the same directory as 'tutorial.xml'

If you're programming in Python

import sys
import gtk
	
class TutorialTextEditor:

    def on_window_destroy(self, widget, data=None):
        gtk.main_quit()
     
    def __init__(self):
    
        builder = gtk.Builder()
        builder.add_from_file("tutorial.xml") 
        
        self.window = builder.get_object("window")
        builder.connect_signals(self)       
    
if __name__ == "__main__":
    editor = TutorialTextEditor()
    editor.window.show()
    gtk.main()

Save this file as 'tutorial.py' in the same directory as 'tutorial.xml'

Compiling and Running the Application 

If you're programming in C

Since C is a compiled language, we need to use the gcc compiler to compile our source code into a binary application. In order for gcc to know where the GTK+ libraries are that it needs to link to and what compiler flags to use, we use a program called pkg-config. When we installed the GTK+ development package, a package-config file named 'gtk+-2.0.pc' was installed on our system. This file tells the pkg-config program which version of the GTK+ libraries are installed and where the include files live on our system. To illustrate this, type the following command in your terminal:

pkg-config --modversion gtk+-2.0

The output should show the version of GTK+ you have installed. On my system it shows '2.12.0'. Now let's look at what compiler flags are needed to build a GTK+ application on my system:

pkg-config --cflags gtk+-2.0

The output of that command shows a bunch of -I switches which are specifying include paths for the compiler to use. This will tell gcc where to look for include files when we use '#include' in our application. The very first one on my system is '-I/usr/include/gtk-2.0'. That means that when I use '#include <gtk/gtk.h>' in my code, gcc will be able to find '/usr/include/gtk-2.0/gtk/gtk.h'.

Anytime you use a '#include <library/header.h>' style include that is not part of the standard C library in your code, there should be a '-I/path/to/library' style option passed to gcc. These libraries can be installed in different locations based on distribution, operating system, or user preference. Good thing we have pkg-config to handle all of this for us!

Let's compile our application so far. Issue this command in the terminal (make sure you are in the same directory in which both 'main.c' and 'tutorial.xml' reside:

gcc -Wall -g -o tutorial main.c -export-dynamic `pkg-config --cflags --libs gtk+-2.0`

The '-Wall' option tells gcc to show all warnings. The '-g' option will generate debugging information which will be useful should you have a bug in your application and need to step through the code using a debugger such as gdb. The option '-o tutorial' tell gcc to generate the output executable into a file named 'tutorial'. 'main.c' is the file gcc will compile. The '-export-dynamic' has to do with how we connect signals to callback functions which will be discussed when we step through the code. And finally, the pkg-config command appears.

Notice how it is enclosed in backticks (those are not single quotes). The backtick is usually to the left of the '1' key on th e keyboard with the tilde character (~). This is telling our shell to first execute the command 'pkg-config --cflags --libs gtk+-2.0' and put the output of that command into the current command. So if you execute 'pkg-config --cflags --libs gtk+-2.0' on your system and then paste it's output onto the end of that gcc command, it would be virtually the same thing. By using pkg-config to append the include paths and library paths to our compile command, we can use the same command to compile our program on any system, regardless of where those libraries are installed.

After your application compiles, there should be a new executable file named 'tutorial' which you execute using:

./tutorial

When you do so, you are going to see several warnings from GTK, something along the lines of " Gtk-WARNING **: Could not find signal handler 'xxxxxx'". Don't worry about those for now. Those are telling use that we specified a signal handler in our glade file which we did not yet write a function for. I'll address these when we step through the code. But you should have seen your GTK+ Text Editor window show up, and clicking the 'x' in the window titlebar should properly terminate the application.

If for some reason you were not able to get the application to compile or execute, post your error messages and any other information in the GTK+ Forums.

If you're programming in Python

Since Python is an Interpreted Language we don't need to compile our program. We simply invoke the Python interpreter, which we actually do with the first line in our source code. So all we need to do to run our Python program, is change the permissions so that the file is executable and then run it. Change the permissions using:

chmod a+x tutorial.py

And now you can run it using:

./tutorial.py

you should have seen your GTK+ Text Editor window show up, and clicking the 'x' in the window titlebar should properly terminate the application.

If for some reason you were not able to get the application to compile or execute, post your error messages and any other information in the GTK+ Forums.

Stepping Through the Code 

Note: You should be looking up each new function in the GTK+ reference documentation as I introduce them. Get to know that documentation, it will be your best friend. Install Devhelp, use it! I will provided a link to the online reference documentation each time I introduce a new function in case you were unable to install Devhelp.

Including the GTK+ Library

If you're programming in C

Hopefully you know enough about C programming to understand the first line '#include <gtk/gtk.h>'. If you don't, you should probably go back and work through a basic C programming tutorial before continuing with this one. By including gtk.h, we are indirectly including a multitude of header files. In fact, with only a few exceptions, we are including all of the GTK+ library and it's dependencies including GLib. If you want to know exactly what is being included just take a look at that file! Essentially, when you're looking through the reference manuals, you have access to most of the functions beginning with gtk_, g_, gdk_, pango_, and atk_.

If you're programming in Python

Hopefully you know enough about Python programming to understand the first two lines '#import sys' and '#import gtk'. If you don't, you should probably go back and work through a basic Python programming tutorial before continuing with this one. We now have access to all gtk.x classes.

Initializing the GTK+ Library

Python implicitly initializes the GTK+ library for you. In C however, we must initialize the GTK+ library before ANY call to a GTK+ function!

If you're programming in C

gtk_init (&argc, &argv);

Looking in 'main()' we see that we initialize GTK+ before anything else using the gtk_init() function.

Building the Interface with GtkBuilder

In a GTK+ application written entirely through code, that is, without the assistance of Glade or another interface designer, we would have to programatically create each widget, set the various properties of that widget, and add it to it's parent widget where applicable. Each of these steps could require several lines of code for each widget. That can be tedious. Just think about the interface we created in part 1. There are over 20 widgets defined (including all the menu items). To create all those widgets through pure code could exceed a hundred lines of lines of code once all the properties were applied!

Good thing we're using Glade and GtkBuilder. With just 2 lines of code, GtkBuilder will open and parse tutorial.xml, create all the widgets defined within, apply their properties, and establish the widgets' parent-child relationships. Once that is done we can then ask builder for the references to the widgets we want to further manipulate or otherwise reference.

Glade and GtkBuilder Conceptual Overview

If you're programming in C

builder = gtk_builder_new ();
gtk_builder_add_from_file (builder, "tutorial.xml", NULL);

The first variable we declared in main() was a pointer to a GtkBuilder object. We initialize that pointer using gtk_builder_new(). This function will create a new GtkBuilder object and return the pointer to that object which we are storing in the 'builder' variable. Just about all GTK+ objects will be created in this fashion.

The builder object at this point hasn't built any UI elements yet. We can use gtk_builder_add_from_file() to parse our XML file 'tutorial.xml' and add it's contents to the builder object.

We are passing NULL as the third parameter to gtk_builder_add_from_file() because we are not going to learn about GError just yet. So we do not have any error checking yet and if the tutorial.xml file is not found or some other error occurs, our program will crash, but we'll address that later.

You will notice that after calling gtk_builder_new() to create a new builder object, all the other gtk_builder_xxx functions take that builder object as the first parameter. This is how GTK+ implements object oriented programming in C, and will be consistent with all GTK+ objects (compare that with how Python, a natural OOP language implements the same thing below).

If you're programming in Python

builder = gtk.Builder()
builder.add_from_file("tutorial.xml")

When we initialize the TutorialTextEditor class with 'editor = TutorialTextEditor()' the class's initialization method, '__init__', is called. The first thing this method does is initialize a new gtk.Builder class with gtk.Builder(). The builder instance is local to the __init__ method because once we build our UI, we will no longer need the builder object.

The builder object at this point hasn't built any UI elements yet. We use gtk.Builder.add_from_file() to parse our XML file 'tutorial.xml' and add it's contents to the builder object.

Getting References to Widgets From GtkBuilder

Once the builder has created all of our widgets we will want to get references to some of those widgets. We only need references to some of the widgets because some of them have already done their job and need no further manipulation. For example, the GtkVBox which holds our menu, text view, and statusbar has already done it's job of laying out our design and our code does not need to access it. So, we need to get a reference to any widget we will manipulate during the lifetime of our application and store it in a variable. At this point in the tutorial, we only need to reference the GtkWindow named "window" so that we can show it.

If you're programming in C

window = GTK_WIDGET (gtk_builder_get_object (builder, "window"));

A couple things are happening here. First, let's look at gtk_builder_get_object(). The first parameter is the object from which we want to get an object. Again, this is how OOP is implemented in C. The second parameter is the name of the object we want to get a pointer to. This corresponds to the 'name' we specified for the widget in Glade during part 1. If you recall, we named the main application GtkWindow 'window'. So, that's what we pass to gtk_builder_get_object().

The gtk_builder_get_object() function returns a pointer to a GObject and we are storing this pointer in 'window' which we declared at the beginning of main() as a pointer to a GtkWidget. Moreover, we know that the object we are trying to get was a GtkWindow. This is why I placed so much emphasis on the 'Object Hierarchy' of widgets and GTK+ objects. If you look at the Object Hierarchy for a GtkWindow you will see that GtkWidget is one of it's ancestors as is GObject. Therefore, a GtkWindow is a GObject and it is a GtkWidget. This is a fundamental OOP concept and critical to working with GTK+.

So, the GTK_WIDGET() wrapped around the call to gtk_builder_get_object() is a convenience macro used for casting. You can cast a GTK+ widget into any of it's ancestors using one of these casting macros. All GTK+ objects will have them available. So, 'GTK_WIDGET(something)' is the same as '(GtkWidget*)something'. We're casting the pointer to a GObject returned from the call to gtk_builder_get_object() to a pointer to a GtkWidget as that's what 'window' was declared as.

Finally, the reason we declared window as a pointer to a GtkWidget in the beginning of main() rather than as a pointer to a GtkWindow is due to convention. We could have declared it as a GtkWindow* and that would have still been correct. All GTK+ widgets are derived from a GtkWidget so we can always declare a variable pointing to any GTK+ widget as such. Many functions take GtkWidget* as a paramter and many functions return GtkWidget* and thus it usually makes sense to declare your variables as such and simply cast them to the specific widget where applicable (which you'll see later).

If you're programming in Python

self.window = builder.get_object("window")

We are using gtk.Builder.get_object() to get the object named "window" from the builder. This corresponds to the 'name' we specified for the widget in Glade during part 1. If you recall, we named the main application's GtkWindow 'window'. So, that's what we pass to get_object(). We assign the returned object to self.window so that we have access to the application's window anywhere within the TutorialTextEditor() class.

Connecting Callback Functions to Signals

In part 1 we specified "handlers" for various "signals" in our interface. If you recall, GTK+ emits signals for various events that occur. This is a fundamental concept of GUI programming. Our application needs to know when the user does something so that it can respond to that action. As we'll see soon, our application just sits around in a loop waiting for something to happen. We will be using GtkBuilder to connect the signal handlers we defined using Glade with callback functions in our code. GtkBuilder will look at our code's symbols and connect the appropriate handlers for us.

In part 1 we specified a handler named 'on_window_destroy' for the "destroy" signal of the GtkWindow named 'window'. Therefore, GtkBuilder will expect to find a function or method named 'on_window_destroy'. The "destroy" signal is emitted when a GtkObject is destroyed. As we'll see in the next bit of code, our application is going to sit in an infinite loop waiting for events to happen. When the user closes the window (such as clicking the 'x' in the titlebar), our application will need to break out of the loop and terminate. By connecting a callback to the "destroy" signal of the GtkWindow we will know when to terminate. Therefore, this is a signal you will use in almost every GTK+ application you write.

Note: The method being used to connect callbacks to signals in this example is equivalent to using glade_xml_signal_autoconnect() function when using LibGlade instead of GtkBuilder.

If you're programming in C

gtk_builder_connect_signals (builder, NULL);

When we call gtk_builder_connect_signals() we pass the builder object as the first parameter as always. The second parameter allows us to pass user data (anything we want) to our callback function. This will be important later, but for now we'll just pass NULL. This function uses GModule, a part of GLib used to dynamically load modules, to look at our applications symbol table (function names, variable names, etc.) to find the function name that matches the handler name we specified in Glade.

In Glade we specified a handler for the GtkWindow's "destroy" signal called 'on_window_destroy'. So, gtk_builder_connect_signals() is looking for a function named 'on_window_destroy' that matches the signature of the callback function for the "destroy" signal. If you recall from part 1, the "destroy" signal belonged to GtkObject. Therefore, we find the prototype for the callback function in the manual for GtkObject under the 'signals' section: GtkObject "destroy" Signal. This tells us what the prototype for our callback function should look like.

Based on the prototype specified in the manual, I wrote the following function:

void 
on_window_destroy (GtkObject *object, gpointer user_data)
{
        gtk_main_quit();
}

So now gtk_builder_connect_signals() will find this function and see that it both matches the name of the handler we specified in Glade and has a compatible signature (takes the same arguments) as that specified for the "destroy" signal and makes the connection. Now our function on_window_destroy() will be called when the GtkWindow 'window' is destroyed.

In on_window_destroy() we just call gtk_main_quit() to properly terminate our application. This function will break out of the main loop which I will talk about more when we get there in just a bit.

Right after the call to gtk_builder_connect_signals() there was a call to g_object_unref().

g_object_unref (G_OBJECT (builder));

This is because we are no longer going to use the GtkBuilder object. We used it to construct our widgets and then we obtained pointers to the widgets we needed to reference. So now we can free all the memory it used up with XML stuff.

You'll also noticed that we are using one of those casting macros to cast (GtkBuilder*) to (GObject*). We must do this because g_object_unref() takes a GObject* as a parameter. Since a GtkBuilder is derived from a GObject (as are all widgets) this is perfectly valid.

If you're programming in Python

builder.connect_signals(self)

In Glade we specified a handler for the GtkWindow's "destroy" signal called 'on_window_destroy'. So, gtk.Builder.connect_signals() is looking for a method named 'on_window_destroy' that matches the signature of the callback method for the "destroy" signal. If you recall from part 1, the "destroy" signal belonged to GtkObject. Therefore, we find the prototype for the callback function in the manual for gtk.Object under the 'signals' section: gtk.Object "destroy" Signal. This tells us what the prototype for our callback method should look like.

Based on the prototype specified in the manual, I wrote the following method:

def on_window_destroy(self, widget, data=None):
    gtk.main_quit()

So now builder.connect_signals() will find this method and see that it both matches the name of the handler we specified in Glade and has a compatible signature (takes the same arguments) as was specified for the "destroy" signal and makes the connection. Now our method on_window_destroy() will be called when the GtkWindow 'window' is destroyed.

In on_window_destroy() we just call gtk.main_quit() to properly terminate our application. This function will break out of the main loop which I will talk about more when we get there in just a bit.

Showing the Application Window

Before we enter the GTK+ main loop (discussed next), we want show our GtkWindow widget as our app doesn't do much good if it's not even visible.

If you're programming in C

gtk_widget_show (window);

Calling gtk_widget_show() sets the Widget's GTK_VISIBLE flag telling GTK+ to show the widget (which will happen within the GTK+ main loop discussed next).

If you're programming in Python

editor.window.show()

Calling gtk.Widget.show() tells GTK+ to show the widget (which will happen within the GTK+ main loop discussed next).

Entering the GTK+ Main Loop

The main loop in GTK+ is an infinite loop which performs all of the "magic". This is how GUI programming works. Once we build our GUI and setup our program, we enter the GTK+ main loop and just wait for an event to occur which we care about (such as closing the window). A lot is happening inside this main loop, however, for a beginner you can simply think of it as an infinate loop in which GTK+ checks the state of things, updates the UI, and emits signals for events.

After entering the main loop, our application isn't doing anything (but GTK+ is). When the user resizes the window, minimizes it, clicks on it, presses keys, etc. GTK+ is checking each of these events and emitting signals for them. However, our application is only connected to one signal currently, the "destroy" signal of 'window'. When the window is closed and the "destroy" signal is emitted, then the GTK+ main loop will turn over control to the handler function we have connected to that signal which breaks us out of the GTK+ main loop thus allowing our application to terminate.

If you're programming in C

gtk_main ();

If you're programming in Python

gtk.main()

In Summary

  1. Application uses GtkBuilder to create the GUI from XML file.
  2. Application gets reference to main window widget.
  3. Application connects 'on_window_destroy' handler to the "destroy" signal.
  4. Application flags the window to be shown.
  5. Application enters GTK+ main loop (window is shown).
  6. User clicks the 'x' in the titlebar as a result of which GTK+ main loop emits the "destroy" signal.
  7. Handler 'on_window_destroy' breaks out of GTK+ main loop.
  8. Application terminates normally.

What's Next? 

In the next part of the tutorial we will begin to move through the code a bit faster, implementing the remaining functionality of our GTK+ text editor entirely through signal handlers.

If you don't want to read along and would rather just see the final implementations:

Did you enjoy GTK+ and Glade3 GUI Programming Tutorial - Part 3? If you would like to help support my work, A donation of a buck or two would be very much appreciated.
blog comments powered by Disqus
Linux Servers on the Cloud IN MINUTES