pyqt5.files.wordpress.com  · web viewyour first gui app with python and pyqt. introduction. many...

31
Your first GUI app with Python and PyQt Introduction Many people struggle with learning how to build a GUI app. The most common reason is, they don’t even know where to start. Most tutorials are purely text based, and it’s hard to learn GUI development using text, since GUIs are mainly a visual medium. We will get around that by building 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 be building:

Upload: hakhanh

Post on 06-Nov-2018

248 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

Your first GUI app with Python and PyQtIntroduction

Many people struggle with learning how to build a GUI app. The most common reason is, they don’t even know where to start. Most tutorials are purely text based, and it’s hard to learn GUI development using text, since GUIs are mainly a visual medium.

We will get around that by building 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 be building:

Page 2: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

A simple GUI app that takes in a price, a tax rate and calculates the final price.

Most tutorials on GUI apps try to layout the GUI blocks using code, but that is very painful to do. We will be using the superb QT Designer tool to layout our app:

Page 3: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

So no struggling laying out the design by hand. Everything will be done graphically.

All the source code is here.

Pre-requisites

If you followed my advice and installed Anaconda, you will already have PyQt4. If not, you will need to get it from here.

You also need Qt Designer.

Update: As Steve points out in the comments, Anaconda comes with qt-designer, so you don’t need to download anything! It is in: …\Anaconda3\Library\bin and is called designer-qt4.exe.

Page 4: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

I recommend you download the whole QT suite, as there are some other useful tools in there too.

Getting Started

Note: You can click on any image below to see the full size, in case you want more detail.

Start QT Designer. In the window that comes up, choose Main Window, as it will give is a blank canvas:

 

The next thing to do is to select the Text Edit box on the left:

Page 5: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

Drag Text Edit to the main window, to get a box like:

Page 6: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

See the right side, where I have clumsily red circled a box? That is where the name of the object is. The name is the way this object will be called from our Python code, so call it something sensible.

Page 7: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

I’m calling it price_box, as we will enter the price into this box. The next thing we will do is attach a label to the box, to make it clear to the user what this box is for.

Page 8: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

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

Page 9: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

It gets the default text of TextLabel. Double click it and change it to Price. You can also make the text large and bold, as seen here:

Page 10: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

For the tax box, we are going to use something different. See the spin box:

Page 11: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

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

Page 12: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

We can choose a default value for our spinbox. I’m choosing 20:

Page 13: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

If you look at the image above, you can also set the minimum and maximum limits. We will keep them to what they are.

We will also add another label called Tax Rate, same as we did before. Also look at the circled Push Button we will be using next:

Page 14: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

 

Now, select the Push Button box and drag it to our window.

Page 15: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

The button just says PushButton, which isn’t very helpful. By now, you should know how to change this. But before that, we change the name of the button (and not the text) to calc_tax_button.

Page 17: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

Drag another Text Edit box on to the window. You don’t need to label it, as we will print the output in here. Do change it’s name to results_window (not shown below, but you should know how to do it by now).

Page 18: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

If you want, you can add a header. This is a simple label box with the font increased:

Page 20: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

This file will be used in the next part when we write the code, so store it somewhere you can access it.

This file that we  created is just a XML file. Open it in a text editor, if you want, and you will find something like this:

Page 21: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

Writing the code

Qt’s code is object oriented, and in  a manner that is easy to follow. Each of the widgets we added is an object, with it’s own functions like toPlainText() (to read the value in a box). This makes it quite easy to use.

I’m sure the official documentation mentions this somewhere, but you have to do some setup before you can use the code. I couldn’t find this setup anywhere, so I worked back from the official examples (as well as other online tutorials) to find the smallest program you need to initialize the class. I have checked this function in as pyqt_skeleton.py.

This is useful, as everytime you start a new PyQt project, use this skeleton to start off, and add your code.

Page 22: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

The code is:

123456789101112131415161718

import sysfrom PyQt4 import QtCore, QtGui, uic qtCreatorFile = "" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MyApp(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:

1 qtCreatorFile = "" # Enter file here.This is where you add the file you created earlier. It is loaded using the inbuilt function:

1 Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) 

Let’s take a quick look at the code:

import sysfrom PyQt4 import QtCore, QtGui

qtCreatorFile = "" # Enter file her

qtCreatorFile = "" # Enter file her

Ui_MainWindow, QtBaseClass =

if __name__ == "__main__": app = QtGui.QApplication(sys. window = MyApp() window.show()

Page 23: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

12345

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

The main code creates a new Qt Gui application. Passing in sys.argv is required, as QT can be configured from the command line. We won’t be doing that.Finally, we create a class called MyApp, which inherits from Qt libraries and initializes the parent classes:

12345

class MyApp(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 that.

Take this file, pyqt_skeleton.py, and rename it to pyqt_first.py. That’s because we don’t want to edit the original file.The first thing to do is add our XML file, the one that contains our GUI, to the code. Replace this line:

1 qtCreatorFile = "" # Enter file here.with

1 qtCreatorFile =  "tax_calc.ui"This will load our GUI file into memory. Now, the key widget in our GUI was the button. Once you press the button, something happens. What? We need to tell our code what to do when the user presses the Calculate Tax button. In the __init__ function, add this line:

class MyApp(QtGui.QMainWindo def __init__(self): QtGui.QMainWindow.__init Ui_MainWindow.__init__(se

qtCreatorFile = "" # Enter file her

qtCreatorFile = "tax_calc.ui"

Page 24: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

1 self.calc_tax_button.clicked.connect(self.CalculateTax)What does this do? 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 the button. All QT widgets have specific functions, which you can find our by Googling. The last part of the code says connect(self.CalculateTax). This says that connect this button to a function called self.CalculateTax, so that everytime the user presses this button, that function is called.

We haven’t written that function yet. Let’s do it now.

In the MyApp Class, add another function. We will look at the whole function first, and then go into details:

123456

    def CalculateTax(self):        price = int(self.price_box.toPlainText())        tax = (self.tax_rate.value())        total_price = price  + ((tax / 100) * price)        total_price_string = "The total price with tax is: " + 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 box, read the tax box, and calculate the final price. Let’s do that now. Remember, we will call the objects by the names we gave them (which is why I asked you not to use the default generic names like box1, as that would have been confusing pretty soon).

1 price = int(self.price_box.toPlainText())We read our price_box. toPlainText() is an internal function that reads the value stored in that box. You don’t have to remember all these functions, by the way. I just Google something like “Qt Textbox read data” to find out what the name of the function is,

self.calc_tax_button.clicked.con

def CalculateTax(self): price = int(self.price_box.toP tax = (self.tax_rate.value()) total_price = price + ((tax /

price = int(self.price_box.toPlainT

Page 25: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

though you will start to remember the names after some time, as they are very logically named.

The read value is a string, so we convert it to an integer and store it in a variable called price.

Next, we read the tax box:

1 tax = (self.tax_rate.value())Again, value() is the function for reading from a spinbox. Thanks, Google.

Now that we have both these values, we can calculate the final price using very high tech maths:

12

total_price = price  + ((tax / 100) * price)total_price_string = "The total price with tax is: " + str(total_price)

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

1 self.results_window.setText(total_price_string)In our results_window, we call the function setText(), which outputs the string we created.

Just run the file using:

tax = (self.tax_rate.value())

total_price = price + ((tax / 100)total_price_string = "The total pr

self.results_window.setText(total

python pyqt_first.py

Page 27: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

And there you go. A simple introduction to PyQt.

If you want more fun, trying playing with the different widgets, though be warned, you can add too many widgets and make your app confusing to use.

Are you interested in seeing more on this? If so, please leave a comment, or contact me.

Page 28: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

89 thoughts on “Your first GUI app with Python and PyQt”

1. Andre says:

March 19, 2015 at 8:23 pm

HiVery interesting tool as Python always lacked a good GUI. Wonder whether this will work on a Raspberry Pi platform?

Regards

Andre

Reply

1. Shantnu says:

March 20, 2015 at 3:01 pm

Hi Andre,

In theory yes, but I have never tried it.

Reply

2. Nelson says:

December 19, 2015 at 1:24 pm

Hi Andre, just tested the code on a RPi2B. It works perfect.

Regards,

Page 29: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

Nelson

Reply

2. John Haddy says:

March 20, 2015 at 5:57 am

I note that Qt is now at revision 5. Is PyQt4 still recommended (over PyQt5)?

Reply

1. Shantnu says:

March 20, 2015 at 3:02 pm

QT5 is the shinier newer version. Unfortunately, it breaks backward compatibility.

I chose PYQy4 merely because it came with my install of Anaconda.

Reply

3. Lemay says:

April 14, 2015 at 6:38 pm

Hi Shantnu,

Awesome guide, really helped me out. Thanks for posting!

I’m a Mechanical Engineer using Qt Designer alongside PySide to develop engineering analysis applications. I would love for some more tutorials on using Qt Designer and its implementation through PySide (or Qt). Specifically, I’m trying to implement plots from matplotlib into a GUI designed using Qt designer.

Any more tutorials/help on this subject matter would be greatly appreciated!

Page 30: pyqt5.files.wordpress.com  · Web viewYour first GUI app with Python and PyQt. Introduction. Many people struggle with learning how to build a GUI app. The most common reason is,

Thanks so much!

-Lemay