Table of Contents
Step 1: Installing Python and GTK in Linux
Step 2: Installing PyGObject in Linux
Creating First PyGObject GUI Application in Linux
Adding More Features to Your PyGObject Application
1. Adding a Label
2. Adding Entry Fields for User Input
3. Styling Your Application with CSS
Conclusion
Home System Tutorial LINUX How to Create GUI Applications In Linux Using PyGObject

How to Create GUI Applications In Linux Using PyGObject

May 13, 2025 am 11:09 AM

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>
Copy after login

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>]    
Copy after login

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>] 
Copy after login

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>]    
Copy after login

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()
Copy after login

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 from Gtk.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 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
Copy after login

A window will appear with a button labeled “Click Me“. When you click the button, “Hello, World!” will be printed in the terminal.

How to Create GUI Applications In Linux Using PyGObject

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()
Copy after login

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.

How to Create GUI Applications In Linux Using PyGObject

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()
Copy after login

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.

How to Create GUI Applications In Linux Using PyGObject

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;
}
Copy after login

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()
Copy after login

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.

How to Create GUI Applications In Linux Using PyGObject

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Does the internet run on Linux? Does the internet run on Linux? Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations? What are Linux operations? Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

What is the salary of Linux administrator? What is the salary of Linux administrator? Apr 17, 2025 am 12:24 AM

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

What are the main tasks of a Linux system administrator? What are the main tasks of a Linux system administrator? Apr 19, 2025 am 12:23 AM

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

What are the differences in virtualization support between Linux and Windows? What are the differences in virtualization support between Linux and Windows? Apr 22, 2025 pm 06:09 PM

The main differences between Linux and Windows in virtualization support are: 1) Linux provides KVM and Xen, with outstanding performance and flexibility, suitable for high customization environments; 2) Windows supports virtualization through Hyper-V, with a friendly interface, and is closely integrated with the Microsoft ecosystem, suitable for enterprises that rely on Microsoft software.

Is it hard to learn Linux? Is it hard to learn Linux? Apr 18, 2025 am 12:23 AM

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

The Future of Linux Software: Will Flatpak and Snap Replace Native Desktop Apps? The Future of Linux Software: Will Flatpak and Snap Replace Native Desktop Apps? Apr 25, 2025 am 09:10 AM

For years, Linux software distribution relied on native formats like DEB and RPM, deeply ingrained in each distribution's ecosystem. However, Flatpak and Snap have emerged, promising a universal approach to application packaging. This article exami

See all articles