Image as background in a Gtk Application.

(Reposted from the old blog)

This time I’m going to talk about putting an image as the application background in Gtk. In Gtk we are used to leave the colors of the application to the theme, but sometimes we will need to use an image as background. I already wrote how to draw a pixbuf in a gtk.DrawingArea (Esp), we could use that, but we will “draw” directly on the widget window instead.

Yes, I said the widget’s window instead the widget itself. You should know that every widget that has been packed in a container has a gtk.gdk.window object and is the responsible for containing your widget. Well, we can draw on that object.

What we need is to create a simple gtk.gdk.Pixbuf and call the gtk.gdk.window.draw_pixbuf method using your widget.window object on the expose-event.

The code should look like this:

#!/usr/bin/env python
import gtk
def draw_pixbuf(widget, event):
        path = '/home/markuz/wallpapers/WMwall1024x768.gif'
        pixbuf = gtk.gdk.pixbuf_new_from_file(path)
        widget.window.draw_pixbuf([gtk.STATE_NORMAL], pixbuf, 0, 0, 0,0)
window = gtk.Window()
window.set_title('Drawing Test')
hbbox = gtk.HButtonBox()
hbbox.connect('expose-event', draw_pixbuf)
button = gtk.Button('Press Me!')
hbbox.pack_start(button, True, False, 10)

And the result should be like this:


Putting an image as background in Gtk

It is just a window with an HBoxButton as container and a Button in the middle. The button draws normal, but the HButtonBox is drawing its gtk.gdk.window with a pixbuf.