Wednesday 23 December 2020

Get started with Python / GTK3 / PyGObject in Ubuntu

 I found myself needing to make a GUI tool for work using a recent version of Ubuntu. These are the steps I followed.


*Install Ubuntu packages needed


sudo apt install pkg-config libglib2.0-dev libgtk-3-dev libgirepository1.0-dev;

You should already have python3 by default.

Note, in Ubuntu 20 you may also need these packages as well for the pycairo/wheels dependency:

sudo apt install libcairo2-dev python3-dev;


*Create a virtual env and set permissions


(Note: You will need to install the package for pip3 for python 3 if it is not already installed)

Choose a location on your machine to hold your python virtualenv, e.g mine will be "/opt/python3".

Find your python 3 path, e.g.

which python3

- mine is /usr/bin/python3


pip3 install virtualenv;


sudo mkdir -p /opt/py3env;

sudo chown scott:scott -R /opt/py3env;

sudo chmod 777 -R /opt/py3env;

virtualenv -p /usr/bin/python3 /opt/py3env;


*Start using the new virtualenv


source /opt/py3env//bin/activate;

pip install --upgrade pip


*Install PyGObject in the virtualenv

pip install pygobject

See the output: 

Successfully installed pycairo-1.20.0 pygobject-3.38.0


*Try a "hello world" program


Save this code in an editor, e.g. as a file named "hello_world.py": 


#!/usr/bin/env python


import gi


gi.require_version("Gtk", "3.0")

from gi.repository import Gtk


window = Gtk.Window(title="Hello World")

window.show()

window.connect("destroy", Gtk.main_quit)

Gtk.main()


*Run the program on the command line:

python hello_world.py





You should see a small GUI window appear! (You might need to stretch it to see its title bar "Hello World")