First impressions of GTK3 migration in Python

Yesterday, I succeeded in moving a GTK2 project* with a custom Cairo widget to GTK3. It's about 750 lines of Python and took ~5 hours to migrate, mainly because my method was about googling and solving all Exceptions one by one. That's not very advisable.

You can read a more thorough introduction to GTK3 and Python here ->

The first thing, you need to know, is that the Python GTK3 bindings are

Step 1:

GTK3/Glib uses different libraries from GTK2, and those libraries conflict with the old ones. So the first part of a migration is to replace ALL occurrences of those imports in your whole project.

Examples of old stuff:

import gtk  
import gobject  
import gtk.gdk  
import cairo  
import pangocairo

# Since GTK 3.6, this is deprecated as it's a no-op. (  
# Thanks @Mathieu Dupuy  

# The below was used on systems with both GTK-1 and GTK-2 and is obsolete.  
# pygtk uses static gobject inheritance different from GTK3.  
# Short version: In GTK3, don't do this!  
import pygtk  

The example above is now:

from gi.repository import Gtk  
from gi.repository import GObject  
from gi.repository Gdk  
from gi.repository import cairo  
from gi.repository import PangoCairo


Step 2:

There are a bunch of changes in the structure of the library. Most constants like gtk.CONSTANT_NAME have changed to something like Gtk.SubLibrary.NAME. For instance, gtk.gdk.LEAVE_NOTIFY_MASK is now Gdk.EventMask.LEAVE_NOTIFY_MASK; gtk.STATE_NORMAL is Gtk.StateFlags.NORMAL; and gtk.EXPAND is Gtk.AttachOptions.EXPAND.

So basically, have a look at everything that's capilized. The following script can help you:

Step 3:

But last thing is that the library has a bunch of changes in the API. Classes, methods, properties, arguments and return values have all changed. So expect the unexpected!

In this regard, you might also find that your project is too complicated for 100% manual conversion. In that case, have a look at:

Examples and tutorials

The following examples are available as of now: