Drawing to GtkLayout and GtkDrawingArea with Python

This one took me several hours to figure out. I’m writing an application that will include a graph of some data collected from the serial port (using the pySerial library). I’m writing the application in Python (2.7.2+) using the GTK 3 framework. UI design is being done in Glade 3. To make the graph, I wanted the base object to be a GtkLayout widget because this widget can be scrolled (inside a GtkScrolledWindow), can contain other widgets, has a fixed layout, and can be directly drawn to.

The problem was, I couldn’t get the draw event for the GtkLayout to trigger no matter what I did. The problem was worsened by the fact that most of the information online is not relevant for Gtk 3, or if it is, it uses the GtkDrawingArea widget instead. But, even when I gave up and went with a GtkDrawingArea widget, I still failed to trigger the draw event.

Finally, after reading everything ever written on the internet, I found the answer in a forum (link below). I was missing the python-gi-cairo package (Debian package) which has the python cairo bindings. After installing this package, the draw event triggers as expected and I’m able to draw to both the GtkLayout and GtkDrawingArea widgets. I didn’t even have to add another “import” line to my script, which is nice, but the dependency still exists.

Link: http://python.6.x6.nabble.com/pygi-gtk-drawingarea-doesn-t-work-td4981920.html

A GtkDrawingArea example: https://git.gnome.org/browse/pygobject/tree/demos/gtk-demo/demos/drawingarea.py

One thought on “Drawing to GtkLayout and GtkDrawingArea with Python”

Leave a Reply

Your email address will not be published. Required fields are marked *