Create More Advance GUI Applications Using PyGobject Tool in Linux


Graphical User Interface (GUI) applications have become an essential part of modern software development. GUIs provide a visually appealing and user-friendly interface for users to interact with the application. In Linux, PyGObject is a powerful tool for developing GUI applications using the GObject introspection library. PyGObject is a Python module that provides bindings for GObject-based libraries, including GTK, GStreamer, and others. In this article, we will discuss how to create more advanced GUI applications using PyGObject in Linux.

What is PyGObject?

GObject is a fundamental object system used by GTK, GStreamer, and other libraries to create object-oriented software in C. PyGObject allows developers to create GUI applications using Python while leveraging the power of GObject-based libraries.

Requirements

Before we start developing GUI applications using PyGObject, we need to install a few dependencies. In this tutorial, we will use the GTK library to create GUI applications. To install the GTK library, run the following command in your terminal −

sudo apt-get install libgtk-3-dev

We also need to install the PyGObject module, which provides the Python bindings for the GTK library. To install PyGObject, run the following command −

sudo apt-get install python3-gi

Once we have installed the necessary dependencies, we can start developing our GUI application using PyGObject.

Creating a Simple PyGObject Application

Let's start by creating a simple PyGObject application that displays a window. Open your favorite text editor and create a new file called simple_app.py. In this file, add the following code −

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

class MyWindow(Gtk.Window):

   def __init__(self):
      Gtk.Window.__init__(self, title="My Window")

win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

Let's go through this code step by step. We first import the gi module and specify that we require version 3.0 of the GTK library. We then import the Gtk module, which provides the main classes and functions for creating GUI applications using PyGObject.

Next, we create a new class called MyWindow, which inherits from the Gtk.Window class. In the __init__ method, we call the parent constructor and set the title of the window to "My Window".

We then create an instance of the MyWindow class and connect the "destroy" signal to the Gtk.main_quit function, which will be called when the user closes the window. Finally, we show the window using the show_all method and start the main loop using the Gtk.main function.

To run this application, open your terminal and navigate to the directory containing the simple_app.py file. Then, run the following command −

python3 simple_app.py

This will open a window with the title "My Window".

Adding Widgets to the Window

Now that we have created a simple PyGObject application, let's add some widgets to the window. Widgets are the building blocks of a GUI application, and they can include buttons, labels, text boxes, and more.

Let's add a label to our window. Modify the MyWindow class in the simple_app.py file to look like this −

class MyWindow(Gtk.Window):

   def __init__(self):
      Gtk.Window.__init__(self, title="My Window")

      # Create a label widget
        self.label = Gtk.Label()

      # Add the label to the window
        self.add(self.label)   

In the __init__ method, we first create an instance of the Gtk.Label class and assign it to the self.label attribute. Then, we add the label widget to the window using the add method of the Gtk.Window class. Now when we create an instance of the MyWindow class and show the window, the label widget will be displayed in the top-left corner of the window. Next, let's set the text of the label to "Hello, World!" and add it to the window. Modify the __init__ method to look like this −

class MyWindow(Gtk.Window):

   def __init__(self):
      Gtk.Window.__init__(self, title="My Window")

      # Create a label
      self.label = Gtk.Label()
      self.label.set_text("Hello, World!")
      self.add(self.label)

We have added two lines of code to set the text of the label to "Hello, World!" and add it to the window using the add method.

Now, when you run the application, you should see a window with the label "Hello, World!".

Adding a Button

Let's add a button to our window that changes the text of the label when it is clicked. Modify the __init__ method of the MyWindow class to look like this −

class MyWindow(Gtk.Window):

   def __init__(self):
      Gtk.Window.__init__(self, title="My Window")

      # Create a label
      self.label = Gtk.Label()
      self.label.set_text("Hello, World!")
      self.add(self.label)

      # Create a button
      self.button = Gtk.Button(label="Click me")
      self.button.connect("clicked", self.on_button_clicked)
      self.add(self.button)

   def on_button_clicked(self, widget):
      self.label.set_text("Button clicked")

We have added a new Gtk.Button widget and assigned it to the self.button instance variable. We have also connected the "clicked" signal of the button to a new method called on_button_clicked. This method will be called when the button is clicked.

In the on_button_clicked method, we set the text of the label to "Button clicked".

Now, when you run the application, you should see a window with a label that says "Hello, World!" and a button that says "Click me". When you click the button, the text of the label should change to "Button clicked".

Next, let's explore some more advanced and complex GUI applications that can be created using PyGObject.

Creating a Calculator Application

Let's create a calculator application that performs basic arithmetic operations.

First, we define a new class CalculatorWindow that inherits from Gtk.Window class. This class is used to create the main window of the application.

class CalculatorWindow(Gtk.Window):

   def __init__(self):
      Gtk.Window.__init__(self, title="Calculator")

Next, we create a grid layout to arrange the widgets in a grid-like structure.

   # Create a grid
   grid = Gtk.Grid()
   self.add(grid)

We create a Gtk.Label widget to display the results of the calculations.

# Create the display label
   self.display = Gtk.Label()
   self.display.set_hexpand(True)
   self.display.set_vexpand(True)
   self.display.set_alignment(1, 0)
   self.display.set_text("0")
   grid.attach(self.display, 0, 0, 4, 1)

Then, we create the buttons for the calculator. Each button is created using the Gtk.Button class and labeled with the corresponding number or operator.

# Create the buttons
   button_7 = Gtk.Button(label="7")
   button_8 = Gtk.Button(label="8")
   button_9 = Gtk.Button(label="9")
   button_divide = Gtk.Button(label="/")
   button_4 = Gtk.Button(label="4")
   button_5 = Gtk.Button(label="5")
   button_6 = Gtk.Button(label="6")
   button_multiply = Gtk.Button(label="*")
   button_1 = Gtk.Button(label="1")
   button_2 = Gtk.Button(label="2")
   button_3 = Gtk.Button(label="3")
   button_subtract = Gtk.Button(label="-")
   button_0 = Gtk.Button(label="0")
   button_decimal = Gtk.Button(label=".")
   button_equal = Gtk.Button(label="=")
   button_add = Gtk.Button(label="+")

We connect the clicked signal of each button to the on_button_clicked method, which is responsible for appending the corresponding number or operator to the current expression being entered.

# Connect the button signals to the handlers
   button_7.connect("clicked", self.on_button_clicked, "7")
   button_8.connect("clicked", self.on_button_clicked, "8")
   button_9.connect("clicked", self.on_button_clicked, "9")
   button_divide.connect("clicked", self.on_button_clicked, "/")
   button_4.connect("clicked", self.on_button_clicked, "4")
   button_5.connect("clicked", self.on_button_clicked, "5")
   button_6.connect("clicked", self.on_button_clicked, "6")
   button_multiply.connect("clicked", self.on_button_clicked, "*")
   button_1.connect("clicked", self.on_button_clicked, "1")
   button_2.connect("clicked", self.on_button_clicked, "2")
   button_3.connect("clicked", self.on_button_clicked, "3")
   button_subtract.connect("clicked", self.on_button_clicked, "-")
   button_0.connect("clicked", self.on_button_clicked, "0")
   button_decimal.connect("clicked", self.on_button_clicked, ".")
   button_equal.connect("clicked", self.on_equal_clicked)
   button_add.connect("clicked", self.on_button_clicked, "+")

We add the buttons to the grid layout, arranging them in a 4x4 grid.

  # Add the buttons to the grid
grid.attach(button_7, 0, 1, 1, 1)
grid.attach(button_8, 1, 1, 1, 1)
grid.attach(button_9, 2, 1, 1, 1)
grid.attach(button_divide, 3, 1, 1, 1)
grid.attach(button_4, 0, 2, 1, 1)
grid.attach(button_5, 1, 2, 1, 1)
grid.attach(button_6, 2, 2, 1, 1)
grid.attach(button_multiply, 3, 2, 1, 1)
grid.attach(button_1, 0, 3, 1, 1)
grid.attach(button_2, 1, 3, 1, 1)
grid.attach(button_3, 2, 3, 1, 1)
grid.attach(button_subtract, 3, 3, 1, 1)
grid.attach(button_0, 0, 4, 1, 1)
grid.attach(button_decimal, 1, 4, 1, 1)
grid.attach(button_equal, 2, 4, 1, 1)
grid.attach(button_add, 3, 4, 1, 1)

We define the on_button_clicked method that handles the click event for each button. This method appends the corresponding character to the current expression being entered.

# Handler for the button click event
   def on_button_clicked(self, widget, char):
      self.expression += char
      self.display.set_text(self.expression)

We also define the on_equal_clicked method that evaluates the current expression and displays the result on the label.

# Handler for the equal button click event
   def on_equal_clicked(self, widget):
      try:
         result = str(eval(self.expression))
         self.display.set_text(result)
         self.expression = result
      except:
         self.display.set_text("Error")
         self.expression = ""

Finally, we create an instance of the CalculatorWindow class and show the main window.

if __name__ == "__main__":
   win = CalculatorWindow()
   win.connect("destroy", Gtk.main_quit)
   win.show_all()
   Gtk.main()

This creates a basic calculator application with a GUI. You can further customize it by adding more functionality or changing the layout and design of the widgets.

Conclusion

PyGObject is a powerful tool for creating GUI applications in Linux. It provides a Pythonic API for the GObject library, which is the underlying C library for GTK+. With PyGObject, developers can easily create complex and sophisticated GUI applications for desktop environments in Linux.

In this article, we covered the basics of PyGObject and demonstrated how to create a simple text editor and a calculator application using the tool. We also explored some advanced features of PyGObject, including creating custom widgets and using CSS for styling.

PyGObject offers a wide range of possibilities for creating GUI applications in Linux. Developers can leverage the capabilities of the tool to build rich and interactive desktop applications that enhance user experience. By combining Python's simplicity and ease of use with the power and flexibility of the GObject library, PyGObject offers a robust solution for creating advanced GUI applications in Linux.

Updated on: 26-Jun-2023

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements