Python GUI Development with GTK+ — Setting Properties

Setting properties

Widgets have properties, properties describe characteristics of the widget such as the widget’s colour, it’s size, angle or the text displayed in it.

In this article, I will show you the three methods available to you to change the properties of widgets. The first method involves setting the properties when creating the widget through keyword arguments.

The following code creates a label with text that is aligned to the center and at an angle of 30 degrees

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

win = Gtk.Window()
label = Gtk.Label(label="Hello World I'm a GUI label", angle=30, halign=Gtk.Align.END)
win.add(label)

win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

The second way to change widget properties is to use getters and setters. The next example shows how to use a setter to set or specify the default size of the Window:

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

win = Gtk.Window()
win.set_default_size(200, 200)

label = Gtk.Label(label="Hello World I'm a GUI label", angle=20, halign=Gtk.Align.CENTER)
win.add(label)


win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

win.set_default_size(200, 200) is a setter for setting the window’s default size. The default size of the window can be retrieved using win.get_default_size().
For the rest of the code I will write from this point on, assume that I have imported the gi module and also handled the main loop and main window’s delete event.

The third way to set widget properties is to use their “props” property. To set the properties of the label using “props” we do:


label = Gtk.Label()
label.props.angle = 30
label.props.label = "Hello World I am a GUI label"
label.props.halign = Gtk.Align.CENTER
win.add(label)

This is equivalent to writing

label = Gtk.Label(label="Hello World I am a GUI label", angle=30, halign=Gtk.Align.CENTER)

To retrieve a widget’s properties using props, you can “dir” the props property:

label = Gtk.Label()
print(dir(label.props))