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 like 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, 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.12.3
If Python is not installed, you can install it using using the following appropriate command for your specific Linux distribution.
sudo apt install python3 [On Debian, Ubuntu and Mint] sudo dnf install python3 [On RHEL/CentOS/Fedora and Rocky/AlmaLinux] sudo apk add python3 [On Alpine Linux] sudo pacman -S python [On Arch Linux] sudo zypper install python3 [On OpenSUSE]
Now, you need to install the PyGObject bindings for Python, as well as GTK development libraries.
sudo apt install python3-gi gir1.2-gtk-3.0 [On Debian, Ubuntu and Mint] sudo dnf install python3-gobject gtk3 [On RHEL/CentOS/Fedora and Rocky/AlmaLinux] sudo apk add py3-gobject gtk+3 [On Alpine Linux] sudo pacman -S python-gobject gtk3 [On Arch Linux] sudo zypper install python3-gobject gtk3 [On OpenSUSE]
Step 2: Installing PyGObject in Linux
Once Python and GTK development libraries are installed, you can now install PyGObject using the following appropriate command for your specific Linux distribution.
sudo apt install python3-gi [On Debian, Ubuntu and Mint] sudo dnf install pygobject3 [On RHEL/CentOS/Fedora and Rocky/AlmaLinux] sudo apk add py3-gobject [On Alpine Linux] sudo pacman -S python-gobject [On Arch Linux] sudo zypper install python3-gobject [On OpenSUSE]
After installation, you’re ready to start developing GUI applications using PyGObject and GTK.
Creating 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.
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
class inherits fromGtk.Window
, which represents the main window of the application. - We create a button using
Gtk.Button
, and the button’s label is set to “Click Me“. We also connect the button’s “clicked” signal to theon_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
A window will appear with a button labeled “Click Me“. When you click the button, “Hello, World!” will be printed in the terminal.
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 label and button one after another. - The
Gtk.Label
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.
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 name 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
is an input field where users can type their name. - The
set_placeholder_text
method shows a hint inside the entry box until the user types something. - After clicking the button, the entered name is retrieved using
get_text()
and displayed in the label as a personalized greeting.
3. Styling Your Application with CSS
PyGObject allows you to apply custom styles to your application widgets using CSS file called style.css
.
window { background-color: #f0f0f0; } button { background-color: #4CAF50; color: white; border-radius: 5px; padding: 10px; } label { font-size: 16px; color: #333; }
Now, modify the Python code to load and apply this CSS file:
import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Gdk class MyApp(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Styled GUI App") self.set_size_request(400, 200) # Load CSS css_provider = Gtk.CssProvider() css_provider.load_from_path("style.css") screen = Gdk.Screen.get_default() style_context = Gtk.StyleContext() style_context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) # 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 CSS Changes:
- The button has a green background, and labels have a custom font size and color.
- The button’s borders are rounded for a modern look.
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.
You can extend these examples to build more complex applications, such as file managers, media players, or even professional-grade software. With PyGObject and GTK, the possibilities for creating desktop applications are nearly limitless!