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 <strong>Python 3.12.3</strong>
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 <strong>Debian, Ubuntu and Mint</strong>] sudo dnf install python3 [On <strong>RHEL/CentOS/Fedora</strong> and <strong>Rocky/AlmaLinux</strong>] sudo apk add python3 [On <strong>Alpine Linux</strong>] sudo pacman -S python [On <strong>Arch Linux</strong>] sudo zypper install python3 [On <strong>OpenSUSE</strong>]
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 <strong>Debian, Ubuntu and Mint</strong>] sudo dnf install python3-gobject gtk3 [On <strong>RHEL/CentOS/Fedora</strong> and <strong>Rocky/AlmaLinux</strong>] sudo apk add py3-gobject gtk 3 [On <strong>Alpine Linux</strong>] sudo pacman -S python-gobject gtk3 [On <strong>Arch Linux</strong>] sudo zypper install python3-gobject gtk3 [On <strong>OpenSUSE</strong>]
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 <strong>Debian, Ubuntu and Mint</strong>] sudo dnf install pygobject3 [On <strong>RHEL/CentOS/Fedora</strong> and <strong>Rocky/AlmaLinux</strong>] sudo apk add py3-gobject [On <strong>Alpine Linux</strong>] sudo pacman -S python-gobject [On <strong>Arch Linux</strong>] sudo zypper install python3-gobject [On <strong>OpenSUSE</strong>]
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!
The above is the detailed content of How to Create GUI Applications In Linux Using PyGObject. For more information, please follow other related articles on the PHP Chinese website!

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

Arch Linux provides a flexible cutting-edge system environment and is a powerfully suited solution for developing web applications on small non-critical systems because is a completely open source and provides the latest up-to-date releases on kernel

Due to its Rolling Release model which embraces cutting-edge software Arch Linux was not designed and developed to run as a server to provide reliable network services because it requires extra time for maintenance, constant upgrades, and sensible fi
![12 Must-Have Linux Console [Terminal] File Managers](https://img.php.cn/upload/article/001/242/473/174710245395762.png?x-oss-process=image/resize,p_40)
Linux console file managers can be very helpful in day-to-day tasks, when managing files on a local machine, or when connected to a remote one. The visual console representation of the directory helps us quickly perform file/folder operations and sav

qBittorrent is a popular open-source BitTorrent client that allows users to download and share files over the internet. The latest version, qBittorrent 5.0, was released recently and comes packed with new features and improvements. This article will

The previous Arch Linux LEMP article just covered basic stuff, from installing network services (Nginx, PHP, MySQL, and PhpMyAdmin) and configuring minimal security required for MySQL server and PhpMyadmin. This topic is strictly related to the forme

Zenity is a tool that allows you to create graphical dialog boxes in Linux using the command line. It uses GTK , a toolkit for creating graphical user interfaces (GUIs), making it easy to add visual elements to your scripts. Zenity can be extremely u

Some may describe it as their passion, while others may consider it a stress reliever or a part of their daily life. In every form, listening to music has become an inseparable part of our lives. Music plays different roles in our lives. Sometimes it


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
