In this tutorial, we're going to write a very simple GTK application that loads and displays an image file. You will learn how to:
Write a basic GTK user interface in Python
Deal with events by connecting signals to signal handlers
Lay out GTK user interfaces using containers
Load and display image files
You'll need the following to be able to follow this tutorial:
An installed copy of the
Basic knowledge of the python programming language
Before you start coding, you'll need to set up a new project in Anjuta. This will create all of the files you need to build and run the code later on. It's also useful for keeping everything together.
Start Anjuta and click File ▸ New ▸ Project to open the project wizard.
Choose PyGTK (automake) from the Python tab, click Continue, and fill out your details on the next few pages. Use image-viewer as project name and directory.
Be sure to disable Use GtkBuilder for user interface as we will build the user interface manually in this example. For an example of using the interface designer, check the .
Click Apply and the project will be created for you. Open src/image_viewer.py from the Project or File tabs. It contains very basic example code.
Let's see what a very basic Gtk application looks like in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
from gi.repository import Gtk, GdkPixbuf, Gdk import os, sys class GUI: def __init__(self): window = Gtk.Window() window.set_title ("Hello World") window.connect_after('destroy', self.destroy) window.show_all() def destroy(window, self): Gtk.main_quit() def main(): app = GUI() Gtk.main() if __name__ == "__main__": sys.exit(main())
Let's take a look at what's happening:
The first line imports the Gtk namespace (that is, it includes the Gtk library). The libraries are provided by GObject Introspection (gi), which provides language bindings for many GNOME libraries.
In the __init__ method of the GUI class creates an (empty) Gtk.Window, sets its title and then connects a signal to quit the application once the window is closed. That's pretty simple overall, more on signals later.
Next, destroy is defined which just quits the application. It is called by the destroy signal connected above.
The rest of the file does initialisation for Gtk and displays the GUI.
This code is ready to run, so try it using Run ▸ Execute. It should show you an empty window.
Signals are one of the key concepts in Gtk programming. Whenever something happens to an object, it emits a signal; for example, when a button is clicked it gives off the clicked signal. If you want your program to do something when that event occurs, you must connect a function (a "signal handler") to that signal. Here's an example:
1 2 3 4 5
def button_clicked () : print "you clicked me!" b = new Gtk.Button ("Click me") b.connect_after ('clicked', button_clicked)
The last two lines create a Gtk.Button called b and connect its clicked signal to the button_clicked function, which is defined above. Every time the button is clicked, the code in the button_clicked function will be executed. It just prints a message here.
Widgets (controls, such as buttons and labels) can be arranged in the window by making use of containers. You can organize the layout by mixing different types of containers, like boxes and grids.
A Gtk.Window is itself a type of container, but you can only put one widget directly into it. We would like to have two widgets, an image and a button, so we must put a "higher-capacity" container inside the window to hold the other widgets. A number of are available, but we will use a Gtk.Box here. A Gtk.Box can hold several widgets, organized horizontally or vertically. You can do more complicated layouts by putting several boxes inside another box and so on.
There is a graphical user interface designer called Glade integrated in Anjuta which makes UI design really easy. For this simple example, however, we will code everything manually.
Let's add the box and widgets to the window. Insert the following code into the __init__ method, immediately after the window.connect_after line:
1 2 3 4 5
box = Gtk.Box() box.set_spacing (5) box.set_orientation (Gtk.Orientation.VERTICAL) window.add (box)
The first line creates a Gtk.Box called box and the following lines set two of its properties: the orientation is set to vertical (so the widgets are arranged in a column), and the spacing between the widgets is set to 5 pixels. The next line then adds the newly-created Gtk.Box to the window.
So far the window only contains an empty Gtk.Box, and if you run the program now you will see no changes at all (the Gtk.Box is a transparent container, so you can't see that it's there).
To add some widgets to the Gtk.Box, insert the following code directly below the window.add (box) line:
self.image = Gtk.Image() box.pack_start (self.image, False, False, 0)
The first line creates a new Gtk.Image called image, which will be used to display an image file. As we need that later on in the signal handler, we will define it as a class-wide variable. You need to add image = 0 to the beginning of the GUI class. Then, the image widget is added (packed) into the box container using GtkBox's method.
pack_start takes 4 arguments: the widget that is to be added to the GtkBox (child); whether the Gtk.Box should grow larger when the new widget is added (expand); whether the new widget should take up all of the extra space created if the Gtk.Box gets bigger (fill); and how much space there should be, in pixels, between the widget and its neighbors inside the Gtk.Box (padding).
Gtk containers (and widgets) dynamically expand to fill the available space, if you let them. You don't position widgets by giving them a precise x,y-coordinate location in the window; rather, they are positioned relative to one another. This makes handling window resizing much easier, and widgets should automatically take a sensible size in most situations.
Also note how the widgets are organized in a hierarchy. Once packed in the Gtk.Box, the Gtk.Image is considered a child of the Gtk.Box. This allows you to treat all of the children of a widget as a group; for example, you could hide the Gtk.Box, which would also hide all of its children at the same time.
Now insert these two lines, below the two you just added:
button = Gtk.Button ("Open a picture...") box.pack_start (button, False, False, 0)
These lines are similar to the first two, but this time they create a Gtk.Button and add it to box. Notice that we are setting the expand argument (the second one) to False here, whereas it was set to True for the Gtk.Image. This will cause the image to take up all available space and the button to take only the space it needs. When you maximize the window, the button size will remain the same, but the image size will increase, taking up all of the rest of the window.
When the user clicks on the Open Image... button, a dialog should appear so that the user can choose a picture. Once chosen, the picture should be loaded and shown in the image widget.
The first step is to connect the clicked signal of the button to a signal handler function, which we call on_open_clicked. Put this code immediately after the button = Gtk.Button() line where the button was created:
This will connect the clicked signal to on_open_clicked method that we will define below.
Now we can create the on_open_clicked method. Insert the following into the GUI class code block, after the __init__ method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
def on_open_clicked (self, button): dialog = Gtk.FileChooserDialog ("Open Image", button.get_toplevel(), Gtk.FileChooserAction.OPEN); dialog.add_button (Gtk.STOCK_CANCEL, 0) dialog.add_button (Gtk.STOCK_OK, 1) dialog.set_default_response(1) filefilter = Gtk.FileFilter () filefilter.add_pixbuf_formats () dialog.set_filter(filefilter) if dialog.run() == 1: self.image.set_from_file(dialog.get_filename()) dialog.destroy()
This is a bit more complicated than anything we've attempted so far, so let's break it down:
The line beginning with dialog creates an Open dialog, which the user can use to choose files. We set three properties: the title of the dialog; the action (type) of the dialog (it's an "open" dialog, but we could have used SAVE if the intention was to save a file; and transient_for, which sets the parent window of the dialog.
The next two lines add Cancel and Open buttons to the dialog. The second argument of the add_button method is the (integer) value that is returned when the button is pressed: 0 for Cancel and 1 for Open.
Notice that we are using stock button names from Gtk, instead of manually typing "Cancel" or "Open". The advantage of using stock names is that the button labels will already be translated into the user's language.
set_default_response determines the button that will be activated if the user double-clicks a file or presses Enter. In our case, we are using the Open button as default (which has the value 1).
The next three lines restrict the Open dialog to only display files which can be opened by Gtk.Image. A filter object is created first; we then add all kinds of files supported by Gdk.Pixbuf (which includes most image formats like PNG and JPEG) to the filter. Finally, we set this filter to be the Open dialog's filter.
dialog.run displays the Open dialog. The dialog will wait for the user to choose an image; when they do, dialog.run will return the value 1 (it would return 0 if the user clicked Cancel). The if statement tests for this.
Assuming that the user did click Open, the next line sets the file property of the Gtk.Image to the filename of the image selected by the user. The Gtk.Image will then load and display the chosen image.
In the final line of this method, we destroy the Open dialog because we don't need it any more.
All of the code you need should now be in place, so try running the code. That should be it; a fully-functioning image viewer (and a whistlestop tour of Python and Gtk) in not much time at all!
If you run into problems with the tutorial, compare your code with this.
Here are some ideas for how you can extend this simple demonstration:
Have the user select a directory rather than a file, and provide controls to cycle through all of the images in a directory.
Apply random filters and effects to the image when it is loaded and allow the user to save the modified image.
provides powerful image manipulation capabilities.
Allow the user to load images from network shares, scanners, and other more complicated sources.
You can useto handle network file transfers and the like, and to handle scanning.
Got a comment? Spotted an error? Found the instructions unclear? Send feedback about this page.