top

10 steps for Getting started GUI`s with python

IntroductionPython programming language is used as a basis for a lot of tools and packages for creating a flexible, usable and reliable desktop application with Graphical User Interface - GUI. These applications can be used for the comfortable launching of Your personal code, functionality, visualizing, management and monitoring of Your tasks.Check out this step by step guide to learn how to build a GUI app in Python from scratch.Step # 1Defining the current task. The very first step in creating a GUI app in Python is what will be solved and estimated as result of the application? The answer to this question will define your next step. Field of the usage is very wide. Data visualizations of the scientific valuations and results, personal applications performance to working with texts, images, additional functions, business automation GUI`s for developing systems and managing tasks, and monitoring. Home use is also fun. Preliminary estimation of the size and functionality of the application is necessary because it is important for choosing GUI toolkit which will fit for these tasks. Gaining a basic understanding of the Python programming language is crucial for any developer to build a desktop application with GUI.Step # 2Second step —Choose a right package for GUI creation and play with GUIs using Python. There exist a number of Python-based packages to do this. As a part of Python standard library -  Tkinter gives you a possibility to create small, simple GUI applications. Most popular Third party related packages: PyQt, PySide, WxPython, Kivy.PyQt - most useful for desktop creation python bindings for the Qt (C++ based) application development framework.PySide - python binding of the cross-platform GUI toolkit Qt. WxPython - the cross-platform GUI toolkit for the Python.Kivy - open source Python library for developing mobile apps and other multitouch application software with a natural user interface.Step # 3We chose a PyQt5 as GUI toolkit for our desktop application. The next step - download and install this package. The best and recommended way is - install Anaconda, powerful and wide functional toolset for using a lot of python related packages.Download link: https://www.anaconda.com/download/and install with instructions. Another way to install PyQt5 - with pip(You must have python 2.x or 3.x installed).Python link: https://www.python.org/downloads/pip install pyqt5Step # 4If installed — we create a file pyqt_app1.py, opening this file with the favorite editor. Importing PyQt5 modules. Creating PyqtApp class. In the _init_function of our class setting window Icon and window title. At the bottom of this file, we create and import instruction of the file with if _name+ == “_main”: and typing lines with importing sys module, calling pyqt base app, calling show() to starting our GUI application.from PyQt5 import QtWidgets, QtGui, QtCore class PyQtApp(QtWidgets.QWidget):         def __init__(self, parent=None):         QtWidgets.QWidget.__init__(self, parent)         self.setWindowTitle("PyQt Application")         self.setWindowIcon(QtGui.QIcon("Your/image/file.png")) if __name__ == "__main__":     import sys     app = QtWidgets.QApplication(sys.argv)     myapp = PyQtApp()     myapp.show()     sys.exit(app.exec_())Step # 5We need to add some style, set size, and position to our application. Let's do this by adding some code. At first set stylesheet in the _init_ function of the main class. Next, set window opacity in the starting file “if” instruction and adding size in both parts of our code. You can change the color of the text and background-color of the window and elements with Your favorite rgba, hex or named color. Just do this with changing the line: self.element.setStyleSheet(“background-color: #hex number or rgba();color: #hex number or rgba(); ”) or self.setStyleSheet(“background-color: #hex number or rgba(); color: #hex number or rgba(); ”) if window styling. setStyleSheet() supporting many styling tags such as width, height, color, background-color, borders, padding, margin and other. All available tags in the Qt documentation. For positioning of the window, we need to get a desktop resolution. Desktop variable describes our desktop parameters. In the main class, we are setting size related to desktop resolution. And we add “else” to the bottom of the file in starting instruction. It makes our code more flexible, for example, if we use this code with other GUI application.from PyQt5 import QtWidgets, QtGui, QtCore class PyQtApp(QtWidgets.QWidget):         def __init__(self, parent=None):         QtWidgets.QWidget.__init__(self, parent)         self.setWindowTitle("PyQt Application")         self.setWindowIcon(QtGui.QIcon("Your/image/file.png"))         self.setMinimumWidth(resolution.width() / 3)         self.setMinimumHeight(resolution.height() / 1.5)         self.setStyleSheet("QWidget {background-color:                            rgba(0,41,59,255);}                            QScrollBar:horizontal {                            width: 1px; height: 1px;                            background-color: rgba(0,41,59,255);}                              QScrollBar:vertical {width: 1px;                            height: 1px;                            background-color: rgba(0,41,59,255);}") if __name__ == "__main__":     import sys     app = QtWidgets.QApplication(sys.argv)     desktop = QtWidgets.QApplication.desktop()     resolution = desktop.availableGeometry()     myapp = PyQtApp()     myapp.setWindowOpacity(0.95)     myapp.show()     myapp.move(resolution.center() - myapp.rect().center())     sys.exit(app.exec_()) else:     desktop = QtWidgets.QApplication.desktop()     resolution = desktop.availableGeometry() Step # 6Let’s add some functionality to our GUI application. The main goal of creating applications with a graphical interface is to build some comfortable interface for using and solving some tasks. We can add buttons, fields, frames, graphics and other things which we want to see on the couch. Buttons and text field would be good for getting effective results. For the best view of the buttons, we create a new class that will describe styling and behavior and set Font.from PyQt5 import QtWidgets, QtGui, QtCore font_but = QtGui.QFont() font_but.setFamily("Segoe UI Symbol") font_but.setPointSize(10) font_but.setWeight(95) class PushBut1(QtWidgets.QPushButton):         def __init__(self, parent=None):         super(PushBut1, self).__init__(parent)         self.setMouseTracking(True)         self.setStyleSheet("margin: 1px; padding: 7px;                            background-color: rgba(1,255,0,100);                            color: rgba(1,140,0,100);                            border-style: solid;                            border-radius: 3px; border-width: 0.5px;                            border-color: rgba(1,140,0,100);")         def enterEvent(self, event):         self.setStyleSheet("margin: 1px; padding: 7px;                            background- color: rgba(1,140,040,100);                            color: rgba(1,140,255,100);                            border-style: solid; border-radius: 3px;                            border-width: 0.5px;                            border-color: rgba(1,140,140,100);")         def leaveEvent(self, event):         self.setStyleSheet("margin: 1px; padding: 7px;                            background-color: rgba(1,255,0,100);                            color: rgba(1,140,0,100);                            border-style: solid;                            border-radius: 3px; border-width: 0.5px;                            border-color: rgba(1,140,0,100);") class PyQtApp(QtWidgets.QWidget):         def __init__(self, parent=None):         QtWidgets.QWidget.__init__(self, parent)         self.setWindowTitle("PyQt Application")         self.setWindowIcon(QtGui.QIcon("Your/image/file.png"))         self.setMinimumWidth(resolution.width() / 3)         self.setMinimumHeight(resolution.height() / 1.5)         self.setStyleSheet("QWidget                            {background-color: rgba(1,255,0,100);}                            QScrollBar:horizontal                            {width: 1px; height: 1px;                            background-color: rgba(0,140,0,255);}                            QScrollBar:vertical                            {width: 1px; height: 1px;                            background-color: rgba(0,140,0,255);}")         self.textf = QtWidgets.QTextEdit(self)         self.textf.setPlaceholderText("Results...")         self.textf.setStyleSheet("margin: 1px; padding: 7px;                                  background-color:                                        rgba(1,255,0,100);                                  color: rgba(1,140,0,100);                                  border-style: solid;                                  border-radius: 3px;                                  border-width: 0.5px;                                  border-color: rgba(1,140,0,100);")         self.but1 = PushBut1(self)         self.but1.setText("")         self.but1.setFixedWidth(72)         self.but1.setFont(font_but)         self.but2 = PushBut1(self)         self.but2.setText("")         self.but2.setFixedWidth(72)         self.but2.setFont(font_but)         self.but3 = PushBut1(self)         self.but3.setText("")         self.but3.setFixedWidth(72)         self.but3.setFont(font_but)         self.but4 = PushBut1(self)         self.but4.setText("")         self.but4.setFixedWidth(72)         self.but4.setFont(font_but)         self.but5 = PushBut1(self)         self.but5.setText("")         self.but5.setFixedWidth(72)         self.but5.setFont(font_but)         self.but6 = PushBut1(self)         self.but6.setText("")         self.but6.setFixedWidth(72)         self.but6.setFont(font_but)         self.but7 = PushBut1(self)         self.but7.setText("")         self.but7.setFixedWidth(72)         self.but7.setFont(font_but)         self.grid1 = QtWidgets.QGridLayout()         self.grid1.addWidget(self.textf, 0, 0, 14, 13)         self.grid1.addWidget(self.but1, 0, 14, 1, 1)         self.grid1.addWidget(self.but2, 1, 14, 1, 1)         self.grid1.addWidget(self.but3, 2, 14, 1, 1)         self.grid1.addWidget(self.but4, 3, 14, 1, 1)         self.grid1.addWidget(self.but5, 4, 14, 1, 1)         self.grid1.addWidget(self.but6, 5, 14, 1, 1)         self.grid1.addWidget(self.but7, 6, 14, 1, 1)         self.grid1.setContentsMargins(7, 7, 7, 7)         self.setLayout(self.grid1) if __name__ == "__main__":     import sys     app = QtWidgets.QApplication(sys.argv)     desktop = QtWidgets.QApplication.desktop()     resolution = desktop.availableGeometry()     myapp = PyQtApp()     myapp.setWindowOpacity(0.95)     myapp.show()     myapp.move(resolution.center() - myapp.rect().center())     sys.exit(app.exec_()) else:     desktop = QtWidgets.QApplication.desktop()     resolution = desktop.availableGeometry()Step # 7As you can see, adding these buttons and text field resized our window and this gives us a flexible view of the application depending on the device and other parameters. Let's write some functions for our app to demonstrate possibilities of the PyQt. The first button on the top will change the background-color and color of our text field.def on_but1(self):     self.textf.setStyleSheet("margin: 1px; padding: 7px;                              background-color: rgba(1,140,0,100);                              color: rgba(1,255,255,100);                              border-style: solid;                              border-radius: 3px;                              border-width: 0.5px;                              border-color: rgba(1,140,0,100);")Step # 8We must connect our button and function for calling event. For this, we add next line to the bottom of the _init_ function of the main class.self.but1.clicked.connect(self.on_but1)Step # 9This step will add images to the application. Second button will be calling a function to copy the path of the image from the text field and put this image to the right bottom corner.Adding QLabel:self.lb1 = QtWidgets.QLabel(self) self.lb1.setFixedWidth(72) self.lb1.setFixedHeight(72)and function:def on_but2(self):     txt = self.textf.toPlainText()     try:         img = QtGui.QPixmap(txt)         self.lb1.setPixmap(img.scaledToWidth(72,                            QtCore.Qt.SmoothTransformation))     except:         passWe are using try/except construction because we are not sure that text in the text field will be a path to the image.Connecting second button and function:self.but2.clicked.connect(self.on_but2)Step # 10Completing and running application. PyQt has a various functionality and gives possibilities to create completely desktop applications. Also provides threading support.Full pyqt_app1.py file looks like this:ConclusionWe described here a very simple example of creating GUI with the Python-based framework — PyQt for developers. This platform provides a lot of possibilities to build fast, functional and flexible applications with a graphical interface, supporting threading with QThread class that solves problems with large functionality and some Python related problems with implementation of the real-time processes. PyQt supporting all available Python standard library gives full toolset for programming to Python-based developers.I created this tutorial to give beginner’s ample insights required to setup Python GUI programming skills in them that helps to get started with building GUI’s using Python. 
Rated 4.0/5 based on 29 customer reviews
Normal Mode Dark Mode

10 steps for Getting started GUI`s with python

Volodymyr Kirichinets
Blog
16th Apr, 2018
10 steps for Getting started GUI`s with python

Introduction

Python programming language is used as a basis for a lot of tools and packages for creating a flexible, usable and reliable desktop application with Graphical User Interface - GUI. These applications can be used for the comfortable launching of Your personal code, functionality, visualizing, management and monitoring of Your tasks.


Check out this step by step guide to learn how to build a GUI app in Python from scratch.


Step # 1

Defining the current task. The very first step in creating a GUI app in Python is what will be solved and estimated as result of the application? The answer to this question will define your next step. Field of the usage is very wide. Data visualizations of the scientific valuations and results, personal applications performance to working with texts, images, additional functions, business automation GUI`s for developing systems and managing tasks, and monitoring. Home use is also fun. Preliminary estimation of the size and functionality of the application is necessary because it is important for choosing GUI toolkit which will fit for these tasks. Gaining a basic understanding of the Python programming language is crucial for any developer to build a desktop application with GUI.


Step # 2

Second step —Choose a right package for GUI creation and play with GUIs using Python. There exist a number of Python-based packages to do this. As a part of Python standard library -  Tkinter gives you a possibility to create small, simple GUI applications. Most popular Third party related packages: PyQt, PySide, WxPython, Kivy.

PyQt - most useful for desktop creation python bindings for the Qt (C++ based) application development framework.

PySide - python binding of the cross-platform GUI toolkit Qt. WxPython - the cross-platform GUI toolkit for the Python.

Kivy - open source Python library for developing mobile apps and other multitouch application software with a natural user interface.


Step # 3

We chose a PyQt5 as GUI toolkit for our desktop application. The next step - download and install this package. The best and recommended way is - install Anaconda, powerful and wide functional toolset for using a lot of python related packages.

Download link: https://www.anaconda.com/download/

and install with instructions. Another way to install PyQt5 - with pip(You must have python 2.x or 3.x installed).
Python link: https://www.python.org/downloads/

pip install pyqt5


Step # 4

If installed — we create a file pyqt_app1.py, opening this file with the favorite editor. Importing PyQt5 modules. Creating PyqtApp class. In the _init_function of our class setting window Icon and window title. At the bottom of this file, we create and import instruction of the file with if _name+ == “_main”: and typing lines with importing sys module, calling pyqt base app, calling show() to starting our GUI application.

from PyQt5 import QtWidgets, QtGui, QtCore
class PyQtApp(QtWidgets.QWidget):
   
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setWindowTitle("PyQt Application")
        self.setWindowIcon(QtGui.QIcon("Your/image/file.png"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    myapp = PyQtApp()
    myapp.show()
    sys.exit(app.exec_())


Step # 5

We need to add some style, set size, and position to our application. Let's do this by adding some code. At first set stylesheet in the _init_ function of the main class. Next, set window opacity in the starting file “if” instruction and adding size in both parts of our code. You can change the color of the text and background-color of the window and elements with Your favorite rgba, hex or named color. Just do this with changing the line: self.element.setStyleSheet(“background-color: #hex number or rgba();

color: #hex number or rgba(); ”) or self.setStyleSheet(“background-color: #hex number or rgba(); color: #hex number or rgba(); ”) if window styling. setStyleSheet() supporting many styling tags such as width, height, color, background-color, borders, padding, margin and other. All available tags in the Qt documentation. For positioning of the window, we need to get a desktop resolution. Desktop variable describes our desktop parameters. In the main class, we are setting size related to desktop resolution. And we add “else” to the bottom of the file in starting instruction. It makes our code more flexible, for example, if we use this code with other GUI application.

from PyQt5 import QtWidgets, QtGui, QtCore
class PyQtApp(QtWidgets.QWidget):
   
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setWindowTitle("PyQt Application")
        self.setWindowIcon(QtGui.QIcon("Your/image/file.png"))
        self.setMinimumWidth(resolution.width() / 3)
        self.setMinimumHeight(resolution.height() / 1.5)
        self.setStyleSheet("QWidget {background-color:
                           rgba(0,41,59,255);}
                           QScrollBar:horizontal {
                           width: 1px; height: 1px;
                           background-color: rgba(0,41,59,255);}  
                           QScrollBar:vertical {width: 1px;
                           height: 1px;
                           background-color: rgba(0,41,59,255);}")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    desktop = QtWidgets.QApplication.desktop()
    resolution = desktop.availableGeometry()
    myapp = PyQtApp()
    myapp.setWindowOpacity(0.95)
    myapp.show()
    myapp.move(resolution.center() - myapp.rect().center())
    sys.exit(app.exec_())
else:
    desktop = QtWidgets.QApplication.desktop()
    resolution = desktop.availableGeometry()



Step # 6

Let’s add some functionality to our GUI application. The main goal of creating applications with a graphical interface is to build some comfortable interface for using and solving some tasks. We can add buttons, fields, frames, graphics and other things which we want to see on the couch. Buttons and text field would be good for getting effective results. For the best view of the buttons, we create a new class that will describe styling and behavior and set Font.

from PyQt5 import QtWidgets, QtGui, QtCore
font_but = QtGui.QFont()
font_but.setFamily("Segoe UI Symbol")
font_but.setPointSize(10)
font_but.setWeight(95)

class PushBut1(QtWidgets.QPushButton):
   
    def __init__(self, parent=None):
        super(PushBut1, self).__init__(parent)
        self.setMouseTracking(True)
        self.setStyleSheet("margin: 1px; padding: 7px;
                           background-color: rgba(1,255,0,100);
                           color: rgba(1,140,0,100);
                           border-style: solid;
                           border-radius: 3px; border-width: 0.5px;
                           border-color: rgba(1,140,0,100);")
   
    def enterEvent(self, event):
        self.setStyleSheet("margin: 1px; padding: 7px;
                           background- color: rgba(1,140,040,100);
                           color: rgba(1,140,255,100);
                           border-style: solid; border-radius: 3px;
                           border-width: 0.5px;
                           border-color: rgba(1,140,140,100);")
   
    def leaveEvent(self, event):
        self.setStyleSheet("margin: 1px; padding: 7px;
                           background-color: rgba(1,255,0,100);
                           color: rgba(1,140,0,100);
                           border-style: solid;
                           border-radius: 3px; border-width: 0.5px;
                           border-color: rgba(1,140,0,100);")
class PyQtApp(QtWidgets.QWidget):
   
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setWindowTitle("PyQt Application")
        self.setWindowIcon(QtGui.QIcon("Your/image/file.png"))
        self.setMinimumWidth(resolution.width() / 3)
        self.setMinimumHeight(resolution.height() / 1.5)
        self.setStyleSheet("QWidget
                           {background-color: rgba(1,255,0,100);}
                           QScrollBar:horizontal
                           {width: 1px; height: 1px;
                           background-color: rgba(0,140,0,255);}
                           QScrollBar:vertical
                           {width: 1px; height: 1px;
                           background-color: rgba(0,140,0,255);}")
        self.textf = QtWidgets.QTextEdit(self)
        self.textf.setPlaceholderText("Results...")
        self.textf.setStyleSheet("margin: 1px; padding: 7px;
                                 background-color:      
                                 rgba(1,255,0,100);
                                 color: rgba(1,140,0,100);
                                 border-style: solid;
                                 border-radius: 3px;
                                 border-width: 0.5px;
                                 border-color: rgba(1,140,0,100);")
        self.but1 = PushBut1(self)
        self.but1.setText("")
        self.but1.setFixedWidth(72)
        self.but1.setFont(font_but)
        self.but2 = PushBut1(self)
        self.but2.setText("")
        self.but2.setFixedWidth(72)
        self.but2.setFont(font_but)
        self.but3 = PushBut1(self)
        self.but3.setText("")
        self.but3.setFixedWidth(72)
        self.but3.setFont(font_but)
        self.but4 = PushBut1(self)
        self.but4.setText("")
        self.but4.setFixedWidth(72)
        self.but4.setFont(font_but)
        self.but5 = PushBut1(self)
        self.but5.setText("")
        self.but5.setFixedWidth(72)
        self.but5.setFont(font_but)
        self.but6 = PushBut1(self)
        self.but6.setText("")
        self.but6.setFixedWidth(72)
        self.but6.setFont(font_but)
        self.but7 = PushBut1(self)
        self.but7.setText("")
        self.but7.setFixedWidth(72)
        self.but7.setFont(font_but)
        self.grid1 = QtWidgets.QGridLayout()
        self.grid1.addWidget(self.textf, 0, 0, 14, 13)
        self.grid1.addWidget(self.but1, 0, 14, 1, 1)
        self.grid1.addWidget(self.but2, 1, 14, 1, 1)
        self.grid1.addWidget(self.but3, 2, 14, 1, 1)
        self.grid1.addWidget(self.but4, 3, 14, 1, 1)
        self.grid1.addWidget(self.but5, 4, 14, 1, 1)
        self.grid1.addWidget(self.but6, 5, 14, 1, 1)
        self.grid1.addWidget(self.but7, 6, 14, 1, 1)
        self.grid1.setContentsMargins(7, 7, 7, 7)
        self.setLayout(self.grid1)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    desktop = QtWidgets.QApplication.desktop()
    resolution = desktop.availableGeometry()
    myapp = PyQtApp()
    myapp.setWindowOpacity(0.95)
    myapp.show()
    myapp.move(resolution.center() - myapp.rect().center())
    sys.exit(app.exec_())
else:
    desktop = QtWidgets.QApplication.desktop()
    resolution = desktop.availableGeometry()


Step # 7

As you can see, adding these buttons and text field resized our window and this gives us a flexible view of the application depending on the device and other parameters. Let's write some functions for our app to demonstrate possibilities of the PyQt. The first button on the top will change the background-color and color of our text field.

def on_but1(self):
    self.textf.setStyleSheet("margin: 1px; padding: 7px;
                             background-color: rgba(1,140,0,100);
                             color: rgba(1,255,255,100);
                             border-style: solid;
                             border-radius: 3px;
                             border-width: 0.5px;
                             border-color: rgba(1,140,0,100);")


Step # 8

We must connect our button and function for calling event. For this, we add next line to the bottom of the _init_ function of the main class.

self.but1.clicked.connect(self.on_but1)

Step # 9

This step will add images to the application. Second button will be calling a function to copy the path of the image from the text field and put this image to the right bottom corner.

Adding QLabel:

self.lb1 = QtWidgets.QLabel(self)
self.lb1.setFixedWidth(72)
self.lb1.setFixedHeight(72)

and function:

def on_but2(self):
    txt = self.textf.toPlainText()
    try:
        img = QtGui.QPixmap(txt)
        self.lb1.setPixmap(img.scaledToWidth(72,
                           QtCore.Qt.SmoothTransformation))
    except:
        pass

We are using try/except construction because we are not sure that text in the text field will be a path to the image.

Connecting second button and function:

self.but2.clicked.connect(self.on_but2)


Step # 10

Completing and running application. PyQt has a various functionality and gives possibilities to create completely desktop applications. Also provides threading support.

Full pyqt_app1.py file looks like this:

Conclusion

We described here a very simple example of creating GUI with the Python-based framework — PyQt for developers. This platform provides a lot of possibilities to build fast, functional and flexible applications with a graphical interface, supporting threading with QThread class that solves problems with large functionality and some Python related problems with implementation of the real-time processes. PyQt supporting all available Python standard library gives full toolset for programming to Python-based developers.

I created this tutorial to give beginner’s ample insights required to setup Python GUI programming skills in them that helps to get started with building GUI’s using Python. 

Volodymyr

Volodymyr Kirichinets

Blog author
Python-based software developer

Leave a Reply

Your email address will not be published. Required fields are marked *

SUBSCRIBE OUR BLOG

Follow Us On

Share on