PyGTK Hello World program for images

Kevin Day, February 2nd, 2008

I’m learning PyGTK to create GUIs with python, but it’s been slow going. My current application primarily uses images, but most of the beginning tutorials for PyGTK use buttons for their “hello world” applications. The PyGTK tutorial is thorough, but I find it easier to work with lots of smaller examples that aren’t as in-depth.

Below is my simple “hello world” application for working with images. When it runs, it displays the first image of a directory. When you click on the image, the next image in the directory is displayed. I kept it basic so that it would be easy to pick up on the PyGTK stuff without getting caught up in other details.

Here’s the code, and below it is a description:

#!/usr/bin/env python
# hello_world_image.py

import pygtk
pygtk.require('2.0')
import gtk

class image:
    def __init__(self):
        self.window = gtk.Window()
        self.event_box = gtk.EventBox()
        self.image = gtk.Image()
        self.image_num = 0
        self.image.set_from_file(self.make_image_name(self.image_num))
        self.event_box.connect("button_release_event", self.change_image)
        self.event_box.add(self.image)
        self.window.add(self.event_box)
        self.window.show_all()

    def make_image_name(self, image_number):
        return "photos/img_" + str(image_number) + ".jpg"

    def change_image(self, widget, event):
        self.image_num += 1
        self.image.set_from_file(self.make_image_name(self.image_num))
        return True

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    image()
    main()

To add an image to a PyGTK application, just create an Image widget with gtk.Image() and tell it where to find the image with the set_from_file method.

The trick is that Image widgets do not react to events (button clicks, key strokes, etc.) so you have to put the Image widget in an Event Box widget. The event box doesn’t take up space in the GUI; it’s just an invisible container that will emit a signal when an event occurs. In this application, the change_image callback function is bound to the event box, but it still operates directly on the Image widget.

For this program to work it assumes that the images are in a folder named “photos” which is in the same directory the application is running in. Also, the images have to be named sequentially: img_0, img_1, img_2, etc. This is how I plan to use the program, but you could just as easily read the contents of the folder into a list and use that for the image names.

Here’s my directory of images:
Image Directory

And here’s my working program:
Hello World w Images

If you’re wondering, it’s not my dog. It’s just an image I found on Flickr.

Hope this little program helps other people starting off with PyGTK.

One Comment:

  • Can’t get this to work at all.

    - Philip Cunningham, October 4th, 2010, 8:02 am