Select Page

Maybe you already know how to make a Python Gui Using PyQt5 or not. Whether you have heard of Qt or not it is here to stay. It’s used by companies and freelance developers alike to build powerful desktop applications everyday. Luckily it is available in an open source version. That means we can leverage the power of the framework to build desktop applications and capitalize on the simplicity of its design for our own implementation. Since it is made for developers it is highly documented which is great news for us as ethical hackers who also want to develop useful apps.

Since Qt framework is so powerful and customizable on every detail the Qt framework has inspired many developers to create bindings to it in other languages. For Python there is an implementation named PyQt. For Go there is the github/therecipe package.

Learning Go? Want to create a GUI but can’t find a good framework? Read my post about Learning Go Gui Creation by Using the Qt package!

Note: this tutorial assumes you are using a Unix or Linux based operating system. If you are using Windows there are tips on performing the same action. (I am between either my MacBook or a Ubuntu VM dedicated to development)

Overview

We are going to do these things in this tutorial:

  • Install Qt Designer
  • Download PyQt5 using the Python3 package manager pip3
  • Create a GUI using Qt Designer and then convert that UI design file into a Python script.
  • Write a Python script to call that converted script effectively running our new MoodChecker app that checks a user’s mood.

Install PyQt5

Unless you are one of those people who enjoys command line tools to a religious fervor there is an easier way. While there are benefits to the many incredible command line tools like nmap and ping, there is no replacement for a well made gui.

Now to create a gui in Python you will need PyQt, and at the time of this writing, PyQt5 is the ideal version. At this junction there are two options to continue:

  • Use Qt Designer to create a .ui file. Convert the file into a callable Python script.
  • Write a Python script that leverages the PyQt5 library to create powerful and highly customizable apps.

I’ll demonstrate both but let’s start with the first option which is generally more beginner-friendly.

Qt Designer – MoodChecker.py

Download and install the Qt Designer application. Get it from https://build-system.fman.io/qt-designer-download. Be sure to choose the “Open Source” option.

Save the file as MoodChecker.ui, ui files are xml files that store all the data required to build your app. Running the app however requires you to port the file into Python. This means you will need to use pyuic5. Not sure if you have the binary or not? Try running this command in a terminal:

which pyuic5

The command should return something like this if it is installed after all.

/usr/local/bin/.../pyuic5

Or if it is not installed it will show as blank. This is most likely an issue you are experiencing before pyqt5 is installed. On Mac issue the command brew install pyqt5. Once that completes, pyuic5 is now installed.

pip3 install pyuic5

For this example we are going to make a simple UI for a mood-checker program. The UI should have at least one input field so that the user can enter a mood they are feeling. Based on the user’s input we will display a message based on how they are feeling.

Python Gui Using PyQt5 – MoodChecker.py

Get started by opening Qt Designer and going to the File tab > New > New Dialog with Buttons Bottom, this will create a new app project.

Next we are going to drag two items to the new app. The first is a LineEdit and a Label.

Save the project as MoodChecker.ui and move on.

Python Gui Using PyQt5

Saving the project as a .ui user-interface file for Qt Designer is enough to launch the project but what about calling the app from the Python interpreter? To do this you need to use the utility that comes with the PyQt5 installation, pyuic5. This tool is designed to be used to convert .ui files into callable Python scripts.

ethicalhacker$ pyuic5 MoodChecker.ui -o MoodChecker.py

In Windows it looks like this:

C:\Users\ethicalhacker\...\PyQt5>pyuic5 MoodChecker.ui -o MoodChecker.py

UI File Converted to Python Script

Once the UI designer file is converted into a Python file you then call the file from another Python script.

Some things to notice here about the converted UI file Python script seen below. The class we will create an instance of is the Ui_Dialog class. In Qt objects are child objects of the QtWidgets parent class. For instance the Ui_Dialog class is a child class of the type QtWidgets.Dialog which lends its properties to use to customize. These include LineEdits which are fields for input by the user and Labels which are helpful text markers indicating information about the area they are displayed next to. There are many more as well such as comboboxes, etc.

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MoodChecker.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.lineEdit = QtWidgets.QLineEdit(Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(170, 70, 113, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(80, 70, 81, 16))
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept)
        self.buttonBox.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Mood Today:"))


This goes in the new Python script, CallMoodChecker.py. Write the following code into CallMoodChecker.py.

from MoodChecker import *
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QMessageBox, QPlainTextEdit


class NewMoodCheckerForm(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(NewMoodCheckerForm, self).__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.buttonBox.clicked.connect(self.CheckMoodUponClick)
        self.show()

    def CheckMoodUponClick(self):
        if self.ui.lineEdit.text() == "sad":
            QtWidgets.QMessageBox.information(self, 'answered sad','you answered %s! cheer up mate!' % self.ui.lineEdit.text())
        elif self.ui.lineEdit.text() == "happy":
            QtWidgets.QMessageBox.information(self, 'answered happy','you answered %s! cheers mate!' % self.ui.lineEdit.text())
        else:
            QtWidgets.QMessageBox.information(self, 'unknown answer','you answered something like %s! anyway cheers mate!' %self.ui.lineEdit.text())



if __name__ == '__main__':


   app = QtWidgets.QApplication(sys.argv)
   window = NewMoodCheckerForm()
   window.show()
   sys.exit(app.exec_())

Let’s break the code down.

# import all the available functions from the MoodChecker library
from MoodChecker import *

In Qt you connect signals to slots. The slot is the custom method here.

#connect the custom mood checker function to the UI Button
self.ui.Button.clicked.connect(self.CheckMoodUponClick)

To retrieve the input the user entered in the LineEdit field you must call the instance ( self.ui ) and the lineEdit along with its callable function text().

self.ui.lineEdit.text()

Upon running the new Python script we see that the app is ready to go.

Python Gui Using PyQt5
Python CallMoodChecker.py and enter your mood! Click Ok to get a response we designed.

Run the new script to call the now-converted .ui file MoodChecker.py to see our app in action!

Python Gui Using PyQt5
There is the custom response message based on the user’s input about their current mood!

That’s all there is to it.

In Conclusion

If you want to develop desktop applications in Python, believe me, I am telling you, use PyQt5. If Go is your language of choice ( me ) read my post, it will save you hours and hours of headache that I had when learning the steps to do it correctly.

To recap, building a real easy but powerful GUI app in Python using PyQt5 you have some options:

  • Use Qt Designer to create a .ui file. Convert the file into a callable Python script.
  • Write a Python script that leverages the PyQt5 library to create powerful and highly customizable apps.
error: