Last Updated:

Creating a simple application in python

Many people struggle to learn how to create a graphical application. The most common reason is that they don't even know where to start. Most tutorials are based solely on text, and it is difficult to learn how to design a graphical interface using text, since graphical interfaces are basically a visual medium.

We'll get around this by creating a simple GUI app and show you how easy it is to get started. Once you understand the basics, it's easy to add advanced stuff.

This is what we will build:

  How to create Simple application in python

 

A simple graphical application that takes the price, tax rate and calculates the final price. Most graphics application tutorials try to compose graphics blocks using code, but this is very painful. We will use the excellent QT Designer tool to layout our application:

How to create Simple application in python

So no need to fight by laying out the design manually. Everything will be done graphically. All source code can be found at github:https://github.com/shantnu/PyQt_first.

Prerequisites

 

If you have Anaconda installed, you will already have PyQt4. If not, you'll need to get it from here: https://riverbankcomputing.com/software/pyqt/download.

You also need QtDesigner. I recommend that you download the entire QT package, as there are some other useful tools out there as well. You can do this at this link: https://www.qt.io/download-open-source

Getting started

Launch QT Designer. In the window that appears, select Main Window, as it will give you a blank canvas:

How to create Simple application in python

The next thing to do is to select the text editing field on the left:

How to create Simple application in python

Drag Text Edit to the main window to get the type field:

How to create Simple application in python

See the right side where I have an ineptly red circled box? That's where the object name is. The name is the way this object will be called from our Python code, so call it something reasonable.

How to create Simple application in python

I call it the price_box, as we will be entering the price into this field. The next thing we'll do is attach the label to the box to let the user know what the box is for.

How to create Simple application in python

Above, I circled the label. Drag it to the main window.

How to create Simple application in python

It gets the default textLabel. Double-click on it and change it to Price. You can also make the text large and bold, as shown here:

How to create Simple application in python

For the tax box, we will use something else. Cm. "spin box" section:

How to create Simple application in python

The circle on the left is a rotating box. This limits the values you enter. We don't need a spinbox, it's just good to see how you can use the different widgets that QT Creator provides. Drag the spin window to the window. The first thing we do is change the name of the object to something reasonable, in our case tax_rate. Remember that this is how this object will be called from Python.

How to create Simple application in python

We can choose a default value for ourspinbox. I choose 20:

How to create Simple application in python

If you look at the image above, you can also set minimum and maximum limits. We will keep them as they are. We'll also add another label called Tax Rate, as before. Also take a look at the circled button we'll use next:

How to create Simple application in python

Now select the keypad and drag it to our window.

How to create Simple application in python

The button just says "Button", which is not very useful. Now you should know how to change that. But before that, we change the name of the button (not the text) to the calc_tax_button.

How to create Simple application in python

Next, we change the text itself:

How to create Simple application in python

Drag another text editing field to the window. You don't need to label it as we will print the result here. Change his name to results_window (not shown below, but you should already know how to do it).

How to create Simple application in python

If you want, you can add a title. This is a simple label box with an enlarged font:

How to create Simple application in python

And save your work:

How to create Simple application in python

This file will be used in the next part when we write the code, so save it somewhere where you can access it. This file we created is just an XML file. Open it in a text editor, something like this:

How to create Simple application in python

Writing code

 

The Qt code is object-oriented and in such a way that it is easy to trace. Each of the widgets we've added is an object with its own functions, such as toPlainText() (for reading the value in the field). This makes it quite easy to use.

I'm sure the official documentation mentions this somewhere, but you have to do some tweaking before you can use the code. I couldn't find this setup anywhere, so I went back to the official examples (as well as other online tutorials) to find the smallest program needed to initialize a class. I tested this feature as pyqt_skeleton.py.

This is useful because every time you launch a new PyQt project, use this skeleton to start and add your code.

The code is as follows:

import sys
from PyQt4 import QtCore, QtGui, uic

qtCreatorFile = "" # Enter the file here.

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

classMyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)

if __name__ == «__main__»:
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())

The main thing to note is line 3:

qtCreatorFile = "" # Enter the file here.

Here you add the file you created earlier. It is loaded using the built-in function:

Ui_MainWindow, QtBaseClass= uic.loadUiType(qtCreatorFile)

Let's take a quick look at the code:

if __name__ == «__main__»:
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())

The main code is created by a new graphical application Qt. Passing sys.argv is necessary because QT can be configured from the command line. We're not going to do that. Finally, we create a MyApp class that inherits from the Qt libraries and initializes the parent classes:

classMyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)

You don't need to know the details of this code. Just use the skeleton and work on it. Take this file pyqt_skeleton.py and rename it to pyqt_first.py. That's because we don't want to edit the source file.

The first thing to do is to add to the code our XML file, the one that contains our GUI. Replace this line:

qtCreatorFile = "" # Enter the file here. And qtCreatorFile ="tax_calc.ui"

This will load our image file into memory. Now the key widget in our GUI was the button. As soon as you press the button, something happens. A what? We need to tell our code what to do when the user clicks the "Calculate Tax" button. In the __init__ function, add this line:

self.calc_tax_button.clicked.connect(self. CalculateTax)

What is this thing for? Remember we called our button calc_tax_button? (This was the name of the object, not the text that was displayed on it.) clicked is an internal function that is called when (surprise) someone clicks on a button. All QT widgets have certain features that you can find on Google.

The last part of the code is connect(self. CalculateTax). This suggests that you connect this button to a function called self. CalculateTax, so that every time the user clicks this button, this function is called.

We haven't written this feature yet. Let's do it now. In the MyApp class, add another function. First, we'll look at the entire feature, and then we'll get down to the details:

defCalculateTax(self):
price = int(self.price_box.toPlainText())
tax = (self.tax_rate.value())
total_price = price + ((tax / 100) * price)
total_price_string = "Total price including tax:" + str(total_price)
self.results_window.setText(total_price_string)

Okay, let's look at the code above, line by line. We have to do two things: read the price field, read the tax field, and calculate the final price. Let's do it now. Remember that we'll be naming objects by the names we gave them (which is why I asked you not to use generic names by default, such as box1, as this would very soon lead to confusion).

price = int(self.price_box.toPlainText())

We already know what price_box. toPlainText() is an internal function that reads the value stored in this field. By the way, you don't have to remember all these features. I just google something like "QtTextboxreaddata" to find out what the function is called, although after a while you'll start remembering the names, since they're very logically named.

The read value is a string, so we convert it to an integer and store it in the price variable. Next, we have a taxbox:

tax = (self.tax_rate.value())

Again, value() is a function for reading from a spin box. Thanks, Google. Now that we have both of these quantities, we can calculate the final price using very high-tech mathematics:

total_price = price + ((tax / 100) *price)
total_price_string = "Total price with tax:" + str(total_price)

We create a line with our final price. This is because we will output this line directly to our application:

self.results_window.setText(total_price_string)

In our results_window, we call the setText() function, which outputs the string we created. Just run the file using:

pythonpyqt_first.py

How to create Simple application in python
How to create Simple application in python

That's it! I hope this article was helpful to you!