Python Notes and Examples

GUI Apps

GTK+ 3

The most up-to-date tutorial for using GTK+ v3 with Python 3 is sebp/PyGobject-Tutorial.

To see demos of GTK3 widgets, install gtk-3-examples and run gtk3-demo and gtk3-widget-factory.

Prereq: (on Debian) you’ll need the python3-gi package installed.

Here’s a Python 3 GObject “Hello World” app, lifted from the tutorial with only minor typographical edits:

#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='Hello World App')
        self.button = Gtk.Button(label='Hello')

        # Connect the "clicked" button event to the `on_button_clicked`
        # callback (and a signal-callback pair is made).
        self.button.connect('clicked', self.on_button_clicked)

        self.add(self.button)

    # A callback function.
    def on_button_clicked(self, widget):
        print('Hello, World!')

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()  # Start the main loop.

When the user does something — say, clicks a button — the main loop delivers an event to GTK. Widgets receive events, and when they do they often emit one or more signals (internal to GTK). When programming, you connect callback functions to various signals. That is, when the widget receives the event, a signal is emitted and your callback functions are called.

Widgets have properties — for example, a button has a “label” property — and you can specify properties in four ways:

See the Python GTK+ 3 tutorial for further details.