PyGObject for Beginners Tutorial

PyGObject is a python module that lets you access GObject-based libraries such as GTK+ within Python. You’ll be able to create GTK+ apps easily by working with PyGObject. It uses GTK+ version 3 and lets you build apps. As the old GTK+ version 2 is now on it’s way out, It is better to switch to GTK + version 3 for building apps.

In order to code with PyGObject, you must have the following dependencies installed.

  • Python 2.7 and Higher
  • gobject-introspection
  • GTK 3

If you’re using latest version of most of the popular distros then you are likely to have the dependencies already installed on your machine. In case if you don’t find these files installed, you can download them manually or install both gobject-introspection and GTK+ on your machine. Once you have these installed on your machine, we’re ready to code.

Type the following code in the text editor and run it.

from gi.repository import Gtk
 
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

In the first line we’re accessing GTK+ classes and functions. In the remaining few lines we’re calling the window() and also accessing the events associated with the window controls. At the end we’re keeping the program in main() loops which is required till we quit the program when the window is closed.

Let’s add few more bits into our code and change few things.

from gi.repository import Gtk
 
class DemoWindow(Gtk.Window):
 
  def __init__(self):
    Gtk.Window.__init__(self, title="Demo Example")
 
win = DemoWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Now as you can see we have added a new class from which we’re calling __init(self) in order to show the window title. Also we’re calling the class name here to invoke the window.

 

That’s it. This completes our simple tutorial on PyGobject.

You can read more in installation and documentation for more reference. I suggest checking out some samples of PyGobject in gnome developer demos. This will help you get the idea on how things work with PyGObject.

You can also find some code examples on PyGobject Tutorial git repository.