A Guide to Creating Python GUI Applications on Linux

Estimated reading: 6 minutes 656 views

Creating graphical user interface (GUI) applications is a fantastic way to bring your ideas to life and make your programs more user-friendly.

PyGObject is a Python library that allows developers to create GUI applications on Linux desktops using the GTK (GIMP Toolkit) framework. GTK is widely used in Linux environments, powering many popular desktop applications, including Gedit, GNOME Terminal, and more.

In this article, we will explore how to create GUI applications under a Linux desktop environment using PyGObject. We’ll start by understanding what PyGObject is and how to install it, and then proceed to building a simple GUI application.

Step 1: Installing Python and GTK in Linux

To work with PyGObject, you need to have Python installed, and most of today’s Linux distributions come with Python pre-installed, but you can confirm by running:

python3 --version

Python 3.10.12

If Python is not installed, you can install it using the following appropriate command for your specific Linux distribution.

apt install python3       [On Debian, Ubuntu and Mint]
dnf install python3       [On RHEL/CentOS/Fedora and Rocky/AlmaLinux]
apk add python3           [On Alpine Linux]
pacman -S python          [On Arch Linux]
zypper install python3    [On OpenSUSE]

Now, you need to install the PyGObject bindings for Python and GTK development libraries.

apt install python3-gi gir1.2-gtk-3.0    [On Debian, Ubuntu and Mint]
dnf install python3-gobject gtk3         [On RHEL/CentOS/Fedora and Rocky/AlmaLinux]
apk add py3-gobject gtk+3                [On Alpine Linux]
pacman -S python-gobject gtk3            [On Arch Linux]
zypper install python3-gobject gtk3      [On OpenSUSE] 

Step 2: Installing PyGObject in Linux

Once Python and GTK development libraries are installed, you can install PyGObject using the following appropriate command for your specific Linux distribution.

apt install python3-gi           [On Debian, Ubuntu and Mint]
dnf install pygobject3           [On RHEL/CentOS/Fedora and Rocky/AlmaLinux]
apk add py3-gobject              [On Alpine Linux]
pacman -S python-gobject         [On Arch Linux]
zypper install python3-gobject   [On OpenSUSE]    

After installation, you’re ready to start developing GUI applications using PyGObject and GTK.

Creating the First PyGObject GUI Application in Linux

Now, let’s build a simple PyGObject application that displays a window with a button. When the button is clicked, it will display a message saying, “Hello, World!“.

Create a Python file called app.py, and let’s start writing the basic structure of our PyGObject application.

nano app.py
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class MyApp(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World App")
        self.set_size_request(300, 100)

        # Creating a button and adding it to the window
        button = Gtk.Button(label="Click Me")
        button.connect("clicked", self.on_button_clicked)
        self.add(button)

    def on_button_clicked(self, widget):
        print("Hello, World!")

# Initialize the application
app = MyApp()
app.connect("destroy", Gtk.main_quit)  # Close the app when window is closed
app.show_all()
Gtk.main()

Explanation of the Code:

  • The first two lines import the necessary PyGObject modules. We specify the GTK version we want to use (3.0 In this case)
  • The MyApp The class inherits fromGtk.Window, which represents the main window of the application.
  • We create a button usingGtk.Button, and the button’s label is set to “Click Me“. We also connect the button’s “clicked” signal to the on_button_clicked method, which prints “Hello, World!” when clicked.
  • The application’s main loop is started by calling Gtk.main(). This loop waits for events (like clicks) and updates the application accordingly.

To run the application, navigate to the directory where you saved the app.py file and run the following command:

python3 app.py
PyGObject GUI Application

Adding More Features to Your PyGObject Application

Let’s now expand our application by adding more widgets and interactivity.

1. Adding a Label

We can enhance our application by adding a Gtk.Label to display messages in the window rather than printing them in the terminal.

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

class MyApp(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Enhanced GUI App")
        self.set_size_request(400, 200)

        # Create a vertical box layout
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        # Create a label
        self.label = Gtk.Label(label="Press the button to see a message")
        vbox.pack_start(self.label, True, True, 0)

        # Create a button
        button = Gtk.Button(label="Click Me")
        button.connect("clicked", self.on_button_clicked)
        vbox.pack_start(button, True, True, 0)

    def on_button_clicked(self, widget):
        self.label.set_text("Hello, World!")

# Initialize the application
app = MyApp()
app.connect("destroy", Gtk.main_quit)
app.show_all()
Gtk.main()

Explanation of the Changes:

  • We used Gtk.Box to organize widgets vertically, which helps us arrange the labels and buttons one after another.
  • The Gtk.Label A widget is added to display a message inside the window.
  • Instead of printing to the terminal, the on_button_clicked function now updates the text of the label.
PyGObject GUI Application with Label

2. Adding Entry Fields for User Input

Next, let’s add Gtk.Entry widgets to allow user input, which will allow us to create a simple application where users can input their names and click a button to display a personalized greeting.

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

class MyApp(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="User Input App")
        self.set_size_request(400, 200)

        # Create a vertical box layout
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        # Create an Entry widget for user input
        self.entry = Gtk.Entry()
        self.entry.set_placeholder_text("Enter your name")
        vbox.pack_start(self.entry, True, True, 0)

        # Create a button
        button = Gtk.Button(label="Submit")
        button.connect("clicked", self.on_button_clicked)
        vbox.pack_start(button, True, True, 0)

        # Create a label to display the greeting
        self.label = Gtk.Label(label="")
        vbox.pack_start(self.label, True, True, 0)

    def on_button_clicked(self, widget):
        name = self.entry.get_text()
        if name:
            self.label.set_text(f"Hello, {name}!")
        else:
            self.label.set_text("Please enter your name.")

# Initialize the application
app = MyApp()
app.connect("destroy", Gtk.main_quit)
app.show_all()
Gtk.main()

Explanation of the Code:

  • The Gtk.Entry It is an input field where users can type their name.
  • The set_placeholder_text The method shows a hint inside the entry box until the user types something.
  • After clicking the button, the entered name is retrieved  get_text() and displayed in the label as a personalized greeting.
PyGObject GUI Application with User Input

Conclusion

PyGObject is a powerful tool for creating GUI applications on the Linux desktop using Python. By leveraging the flexibility and simplicity of Python along with the rich features of GTK, developers can create feature-rich and visually appealing applications.

In this guide, we covered the basics of setting up PyGObject, creating a simple window, handling button clicks, adding user input, and even applying custom CSS styles.

Share this Doc

A Guide to Creating Python GUI Applications on Linux

Or copy link

CONTENTS