How to create GUI's in Python using PyQt5

How to create GUI's in Python using PyQt5

This Python GUI tutorial covers the basics of how to create GUI's in Python using PyQt5. You'll learn how to install PyQt5, how to find the designer and basic usage, converting .ui to .py, running the output file and connecting events to methods.

This tutorial covers the basics of how to create GUI's in Python using PyQt5. I will demonstrate how to find the designer and basic usage, converting .ui to .py, running the output file and connecting events to methods.

Table Content

  • Setting up the Environment
  • Using the Designer
    • Locating
    • Using the Designer
      • Creating a Simple Window
  • Converting .ui to .py
  • Running the Output and Hooking up the Button
  • More Advanced Example
    • Creating Interface
    • Connecting Events to Methods
      • Linking the Image Button
      • Linking the Add to List Button
  • Common Issues and Questions
    • Could not find a version that satisfies the requirement pyqt5-tools
Setting up the Environment

For this tutorial you will need a version of Python equal to or above 3.5. I do however recommend to get a more recent version than 3.5 as I had issues with 3.5.2; a simple upgrade to 3.6.6 fixed this. If you don't know where to get Python, look here.

Now you will want to install pyqt5 and pyqt5-tools. To do this, we can use pip. Call the two commands python -m pip install pyqt5 and python -m pip install pyqt5-tools. After each command completes, make sure to verify that they installed properly by checking if it says they were installed successfully.

You should now be able to execute the following in Python with no errors:

import PyQt5

If you have issues installing PyQt5 for some reason, you could try the installers at its sourceforge page.

Using the Designer

When you ran the pip install pyqt5-tools command, this installed tools that we can use to help with building GUIs.


First we need to locate where they are now, to do this we can run the following code in Python:

import site
print (site.getsitepackages())

This will print out a couple of paths, for me it prints: ['C:\\Python36', 'C:\\Python36\\lib\\site-packages']. Here we can see my Python distribution location and the site-packages folder. Open up a file explorer and navigate to the site-packages folder. In this folder you then want to locate the pyqt5-tools folder and open it. In this folder you should find a few files, one named designer.exe.

After recent updates to pyqt5-tools, designer.exe has been moved to the 'Scripts' folder in your Python distribution. To find this using the paths we found before, go to the first path returned ('C:\Python36' in my case) and then go into the 'Scripts' folder; you should find designer.exe in here.

Using the Designer

designer.exe is the program that we will use to make designing GUIs a lot easier; remember the location of this or create a shortcut to it and then run it (double click if you wish). You will be welcomed with a selection window; select "Main Window" and then click "Create".

You will now be shown an empty window in the middle of the designer's window with widget options on the left and some other windows to the right.

On the left you can drag widgets from the drop-downs onto the MainWindow object in the center. On the right in the Object Inspector you can see the current widgets in your window. Right below that is the Property Editor that allows you to modify the widget currently selected.

Creating a Simple Window

For this example, we will be just putting a button that prints "Hello World!" when pressed in the Window; soon we will work with a larger example when the basics are out of the way.

First make your window a bit smaller by clicking and dragging the bottom right of the window (or any part on the edge) to change the size as you would do on any other window. Now find the "Push Button" widget under the Buttons section (on the left) and drag it into the window anywhere. You can double click on the button now to rename the text in it; set it to "Print Message".

You may now want to change the size of the button, to do this click on the button until there are blue squares on each of it's corners and edges. Use these blue squares to re-size the button to a size you want.

When you are happy with what you have done (this is just a simple practice) then click File -> Save in the top left and save it somewhere where you will remember; I will save it as 'printMessage.ui' on my desktop.

Converting .ui to .py

Now that we have our .ui file, we can convert it into Python code so we can modify and run it.

To do this we need to located pyuic5. pyuic5 converts .ui to .py in one simple command and is located in the 'Scripts' folder in your Python distribution. If you don't know where this is, execute the following:

import sys
import os
print (os.path.dirname(sys.executable))

You will be provided a path of where your python distribution is located; mine is at C:\Python36 (we saw this before when looking for the designer). Now go to this directory and the open the 'Scripts' folder in there.

In this folder you will see a few executables to make Python in the terminal easier, you should also be able to see a file named pyuic5.exe; this is what we are going to use. Open cmd and then use the cd command to get to the directory; for example I will execute cd C:\Python36\Scripts in cmd. Now if you type pyuic5 you should be provided a small error message saying "Error: one input ui-file must be specified"; this is good, we are in the right place.

To convert we now need to pass in the .ui file we created before and decide on an output filename and location. My .ui file is on my desktop currently so I will put the created .py file on the desktop also to make it easier. Now we can convert using pyuic5 -x <.ui file> -o < file>, for example I will use pyuic5 -x "C:\Users\Brent\Desktop\printMessage.ui" -o "C:\Users\Brent\Desktop\". This should take not very long at all and show no errors; the python script you declared after -o will now exist - for me a file called is now on my desktop.

Running the Output and Hooking up the Button

Now that you have the .py file containing the ui code, open it in IDLE or whatever IDE you use. Your code should look something like this:

Run the code and then wait for the GUI to appear; it currently won't do anything when you press the button so we will set that up.

Go back into the code for this GUI and look in the setupUi definition. You should see a class variable called self.pushButton which later has its text set to "Print Message" in the retranslateUi definition below. This is the object of our button that we need to make do something.

First we need to create our method, this method can be in the global scope or in the class scope, for simplicity I will put it in the class scope. After the retranslateUi definition, create a new class called printMessage that takes self as an argument since it is part of the class now. Inside this put what you want the script do to when you press the button, for this example I will print "Hello World!".

def printMessage(self):
    print ("Hello World!")

Now that you have created the method to run, we can attach it to the button. Using the button variable we found before, we can call .clicked.connect() on it passing in the name of our method we just created (make sure to remember self. for class variables). Put this line at the bottom of the setupUi definition so it will be executed when the GUI is built.


Remember to not include () when passing the method here or it will not work.

Your script should now look something like this, don't worry if it is a bit different.

Run the code again and now when you press the button you should see that the script runs your code that you defined in the method you attached to the button.

More Advanced Example

In this next example I will show you how to put images in the GUI, add a selection dialog box and add data to a table.

Creating Interface

Open the designer back up and create a new MainWindow. Now create and position the 5 widgets described below: - Label (in Display Widgets): This label will be the widget we use to show the image - PushButton (in Buttons): This button will allow us to select the image to show in the Label - ListWidget (in Item Widgets): This will hold and display entries we add to it - LineEdit (in Input Widgets): This will allow us to enter what we want into the table - PushButton (in Buttons): This will add the item in the LineEdit to the table

If you click on a widget, for example the button that will be selecting the button, the Property Editor on the right will display all the options for that object. In there you can edit things like the exact size/position, borders (frames), tooltips and fonts.

First we will want to edit the Label that is holding the image; click on the label to open it up in the Property Editor. Find "text" under the QLabel section and delete the text, this is the same as double clicking and removing the text. Now go to the QFrame heading and change "frameShape" to box, this will but a border around the image.

Now click on the select image button and in the QWidget header go to "font". This has many options inside of this so play around to get a font you like (you can leave it if you want). Your GUI should now look something like this:

To help you later on, you can also change the "objectName" under QObject in the Property Editor for all widgets so you can identify them easier later. Here is what I named mine: - Select Image Button: selectImageBtn - Image Label: imageLbl - LineEdit: lineEdit - Add button: addBtn - ListWidget: listWidget

Like we did before, convert this .ui file (after saving it) to a .py file.

Connecting Events to Methods

Now we need to connect all the actions together. The select image button will need to be connected to a method that displays an image selection dialog which will then put an image in the label. Also we will need to make the 'add' button add the text in the lineEdit object into the listWidget object.

If you open your .py file in IDLE, you can see that the names we gave each widget have passed through to the names of the actual objects. I also recommend to run the code now to make sure it is running.

Linking the Image Button

First you will want to create a class definition called setImage; make sure this takes self as it is a class definition. In this method we want to ask the user for an image (not just any file). If they provide a file, we then need to create a pixmap object and then set the pixmap object to the image label. Before we set it, it is ideal to scale the image to fit inside the label without stretching and aligning it to the centre. Your method will look like this:

def setImage(self):
    fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Image", "", "Image Files (*.png *.jpg *jpeg *.bmp)") # Ask for file
    if fileName: # If the user gives a file
        pixmap = QtGui.QPixmap(fileName) # Setup pixmap with the provided image
        pixmap = pixmap.scaled(self.imageLbl.width(), self.imageLbl.height(), QtCore.Qt.KeepAspectRatio) # Scale pixmap
        self.imageLbl.setPixmap(pixmap) # Set the pixmap onto the label
        self.imageLbl.setAlignment(QtCore.Qt.AlignCenter) # Align the label to center

In the QtWidgets.QFileDialog.getOpenFileName method call, you can see I have passed the string "Image Files (*.png *.jpg *jpeg *.bmp)". This declares the type of files I will accept. If you want to accept any file, remove this string completely. If you want to make it so the user could switch it to all files themselves, set it to "Image Files (*.png *.jpg *jpeg *.bmp);;All Files (*)"; play around with this to get the idea of what is going on, you can add more file extensions and selections if wanted.

Now we need to attach the button to the definition. This can simply be done using the connect method we used previously; make sure to put it at the bottom of the setupUi definition like we did before:


Run the script and make sure that your button works. Initially the label will be clear but each time you select a file it should change to the selected file.

Linking the Add to List Button

We will now need to create another class definition called addItem like before. In this method we need to get the value of the lineEdit object and then clear it. We can then simply add the value we just got to the listWidget. After you have done that, the method should look like this:

def addItem(self):
    value = self.lineEdit.text() # Get the value of the lineEdit
    self.lineEdit.clear() # Clear the text
    self.listWidget.addItem(value) # Add the value we got to the list

And then like before, we need to connect the button to the method just under the last one we did:


Running the script now you should be able to type in the text edit item and then press add for the item to go into the list.

Python Tutorial - Learn Python for Machine Learning and Web Development

Python Tutorial - Learn Python for Machine Learning and Web Development

Python tutorial for beginners - Learn Python for Machine Learning and Web Development. Can Python be used for machine learning? Python is widely considered as the preferred language for teaching and learning ML (Machine Learning). Can I use Python for web development? Python can be used to build server-side web applications. Why Python is suitable for machine learning? How Python is used in AI? What language is best for machine learning?

Python tutorial for beginners - Learn Python for Machine Learning and Web Development


  • 00:00:00 Introduction
  • 00:01:49 Installing Python 3
  • 00:06:10 Your First Python Program
  • 00:08:11 How Python Code Gets Executed
  • 00:11:24 How Long It Takes To Learn Python
  • 00:13:03 Variables
  • 00:18:21 Receiving Input
  • 00:22:16 Python Cheat Sheet
  • 00:22:46 Type Conversion
  • 00:29:31 Strings
  • 00:37:36 Formatted Strings
  • 00:40:50 String Methods
  • 00:48:33 Arithmetic Operations
  • 00:51:33 Operator Precedence
  • 00:55:04 Math Functions
  • 00:58:17 If Statements
  • 01:06:32 Logical Operators
  • 01:11:25 Comparison Operators
  • 01:16:17 Weight Converter Program
  • 01:20:43 While Loops
  • 01:24:07 Building a Guessing Game
  • 01:30:51 Building the Car Game
  • 01:41:48 For Loops
  • 01:47:46 Nested Loops
  • 01:55:50 Lists
  • 02:01:45 2D Lists
  • 02:05:11 My Complete Python Course
  • 02:06:00 List Methods
  • 02:13:25 Tuples
  • 02:15:34 Unpacking
  • 02:18:21 Dictionaries
  • 02:26:21 Emoji Converter
  • 02:30:31 Functions
  • 02:35:21 Parameters
  • 02:39:24 Keyword Arguments
  • 02:44:45 Return Statement
  • 02:48:55 Creating a Reusable Function
  • 02:53:42 Exceptions
  • 02:59:14 Comments
  • 03:01:46 Classes
  • 03:07:46 Constructors
  • 03:14:41 Inheritance
  • 03:19:33 Modules
  • 03:30:12 Packages
  • 03:36:22 Generating Random Values
  • 03:44:37 Working with Directories
  • 03:50:47 Pypi and Pip
  • 03:55:34 Project 1: Automation with Python
  • 04:10:22 Project 2: Machine Learning with Python
  • 04:58:37 Project 3: Building a Website with Django

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

Python Programming Tutorial | Full Python Course for Beginners 2019 👍

Top 10 Python Frameworks for Web Development In 2019

Python for Financial Analysis and Algorithmic Trading

Building A Concurrent Web Scraper With Python and Selenium

Using Scikit-Learn for Machine Learning Application Development in Python

Using Scikit-Learn for Machine Learning Application Development in Python

Using Scikit-Learn for Machine Learning Application Development in Python - Python is arguably the best programming language for machine learning. However, many aspiring machine learning developers don’t know where to start...

Using Scikit-Learn for Machine Learning Application Development in Python - Python is arguably the best programming language for machine learning. However, many aspiring machine learning developers don’t know where to start...

They should look into the scikit-learn library, which is one of the best for developing machine learning applications. It is free and relatively easy to install and learn.

Why Machine Learning Programmers Should Be Familiar With Scikit-Learn

If you are trying to develop machine learning applications, then you were going to need a robust toolkit. Scikit-learn is just the solution that you need. This library was developed in 2007 as part of a Google project. Three years later, the code was released as hey solution for machine learning algorithms in conjunction with Google and several other major companies.

Scikit-learn is a library that contains several implementations of machine learning algorithms. There are two essential classifiers for developing machine learning applications with this library: a supervised learning model known as an SVM and a Random Forest (RF).

There are numerous reasons that scikit-learn is one of the preferred libraries for developing machine learning solutions. Some of the Premier benefits include:

  • Regression modeling
  • Unsupervised classification and clustering
  • Decision tree pruning and induction
  • Comprehensive and neural network training with regression and classification algorithms
  • Decision boundary learning with SVMs
  • Advanced probability modeling
  • Feature analysis and selection
  • Reduction of dimensionality
  • Outlier detection and rejection

Scikit-learn has been used in a number of applications by J.P. Morgan, Spotify, Inria, and other major companies. Machine learning applications built with scikit-learn include financial cybersecurity analytics, product development, neuroimaging, barcode scanner development, medical modeling and help with handling Shopify inventory issues.

The wide range of decision modeling features makes scikit-learn. One of the most versatile machine learning environments available in any programming language. Intermediate and advanced Python programmers should be able to master the nuances of this sophisticated library in a matter of hours.

The scikit-learn library is not installed by default. Fortunately, you should be able to set it up quickly. Here are some guidelines for installation and creating the foundation for your first machine learning project.

Installation of Scikit-Learn

If you already have pip installed, it's very easy to install the scikit-learn library. The instructions are available on this page.

Data for Audio

The purpose of using classification is to create a model based on the representation of a phenomenon in vector form (i.e. as a vector) and its corresponding class. This model will then be used to assign a class to an unknown vector. MFCCs can be used for approximations of sound vectors. MFCC provides 13 values per window. One option is to try classifying the class of a sound using those values. However, the sequences of the sound are very important.

This approach resolves some vector problems. The first approach we can follow is to take a segment of MFCCs and average them. Rather than having 13 values for the size of the segment, we end up with thirteen values. Averaging them is very simple, but we can get other statistics, such as: standard deviations and quartiles. This strategy provides statistical representations of all variables.

Loading Data From a CSV File

You will save your scikit-learn data in CSV files. Each line represents a line and each regular column represents a dimension of the vector. In general, the latter represents the class. Rows are separated by a line break and columns by a column. An illustrative example would be as follows:

event_1,event_2, event_label

To upload a file you can execute the following code:

import numpy as np

At the end of this code, the variable data contains our data. The file scikit_1.csv contains segment data..

Separating Different Data Types

In order to learn a model, we need to follow the methodology presented at the beginning. We are not going to be able to follow it to the letter, but we are going to do our best to make our model the best. The first step is to hide some examples to consider them as evidence.

scikit learn prefers separate data between dimensions and classes.

Here is the code that accomplishes this step:


The first line brings $2233$ dimensions of our vectors (in this case we are ignoring those derived from these data). The data will be stored in the variable $First_variable$. The variable $Second_variable$ stores the classes (all lines, last column).

Scikit learn contains a function that allows separating the training data from the test data, and this is done automatically and shuffles the data randomly that supports our methodology.

We have four sets; two versions of the dimension data we generally call features and two versions of the classes. One version is for training (train), and another for testing (test). The train versions have half of the original data, while testing the other half.

Learn Python 3 from scratch to become a developer in demand

Learn Python 3 from scratch to become a developer in demand

Learn Python 3 from scratch to become a developer in demand

This is the most comprehensive yet simple course on python programming language and it concentrates on Python 3.x which means that what you will learn is relevant and is not obsolete.=

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Python is one of the most useful programming languages to learn

You can back-end of web applications, games, in-house scripts and even build robust test automation framework.

You will get the best in class support from the instructor for any question you have related to the course.

This course is very well structured:

Each lecture consist of a video screencast and code files
There are quizzes, homework to test your knowledge
High focus on practice and asking questions
You will also learn coding best practices
In recent years demand for python has exploded the job market and there are not as many developers as open jobs because not just development, QA industry is rapidly transitioning to python and building automation tools

What are you waiting for? Enroll today and learn the powerful python language !!!

Who is the target audience?

Beginners with zero programming background
Experienced programmers with other programming language
Testers who want to automate tools
Basic knowledge
Computer access with internet access
Nothing else, all the basics and set up information is covered in the course
What will you learn
Understand the concepts of Object Oriented Programming Language
Understand and write Efficient Code
Use Python Language to develop back-end of Web Applications
Use Python Language to create Games
Use Python Language to build Automation Frameworks
Use Python Programming Language to create your own hobby projects