Use PYQT to write the first Python GUI program

Source: Internet
Author: User
Tags qt designer

This article by Bole Online-Lane translation, Daetalus School Draft. without permission, no reprint!
English Source: pythonforengineers.com. Welcome to join the translation team.

Brief introduction

Many people find it difficult to learn how to create a GUI application. The most important reason is that they do not know where to begin. Most tutorials have only text, but in fact it's hard to learn GUI programming just by writing, because most of the GUI applications are visually based.

We will avoid the above mentioned problems by creating a simple GUI application and show you how simple it is to get started. Once you understand these basic knowledge, further study will become very easy.

This is what we are about to accomplish:

This is a simple GUI application that calculates the final price, based on the price entered and the tax rate.

Most tutorials try to lay out the GUI application directly from the code, but it's hard to do so. What we're going to do is use the excellent QT Designer tools to lay out our apps.

So don't bother to design the interface with code. Now everything is going to be done through the graphical interface.

All the code is here.

Pre-conditions

If you have accepted my suggestion and installed Anaconda, you should have installed PYQT4. If not, you need to download it from here first.

You also need a Qt Designer. I recommend that you download the entire QT suite, as it also contains many other useful tools.

Get Started

Tip: When you need to see more details, you can view the original image by clicking on any of the images below. (Translator Note: You may need to view the original link to view the artwork)

Open QT Designer. In the pop-up window, select Main window, so it will give you a blank artboard.

Next, select on the left Text Edit :

Text EditDrag to the main window:

See the right side of my rough red circle frame up the part? That's where the name of the object is defined. This name will be the variable name that we call to this object through Python code, so try to get a meaningful name.

I'll name it price_box because we'll enter the price here. Then we need to add a label to the input box to let the user know more about what the input box does.

I circled the label in the middle. Drag it to the main window.

Now it is called by default TextLabel . Double-click and name it Price . You can also make the text larger and bold, as seen below:

For the tax-rate input box, we'll use something else. Find spin box :

The left side of the circle frame is one of the parts spin box . It will limit the values you can enter. It doesn't have to be used spin box , but it's just to better showcase the different components that QT Creator can offer. Is spin box dragged into the window. And then the first thing we're going to do is objectName change to a meaningful name, like I set it to tax_rate . Keep in mind that this will be the variable name you will use when calling it in Python code.

We can spin box set a default value for our. I chose to set it to 20:

If you look closely, you will find that we can also set its minimum and maximum values. But I'm not going to change them.

Similarly, I will add a label to it called Tax Rate . And see what we're going to use next Push Button :

OK, now select Push Button and drag it into our window.

This button now shows that PushButton this is not a meaningful name. At this stage, you should know how to change it. But before we do, we have to change the name of the button (not the text column shown) calc_tax_button .

We can then modify the actual display text column:

Then select the other one Text Edit and drag it into the window. You don't need to tag it, because we're going to export our results here. Change its name to results_window (not in the picture, but you should already know how to do it).

If you feel the need, you can add a headline. This is a simple label box and the font is enlarged.

Save your results now:

This file will be used when we write the code in the next section, so it's best to have it in a place where we can easily access it.

We created just a simple XML file. Open it with any text editor and you can see something like this:

Writing code

Qt code is object-oriented and easy to learn. All of the components we add are an object and have their own methods such as toPlainText() (to read the values in the input box). This makes it very convenient to use.

Before you write your code, you have to use some functions to configure it. I'm sure there's something about this in the official documentation, but I can't find these documents right now, so I can only use the official routines (and some tutorials on the web) to summarize this little piece of code to configure. I've uploaded these functions to the pyqt_skeleton.py.

The code is very useful, and whenever you want to create a new PyQt project, add your own code based on this code.

This code is as follows:

123456789101112131415161718 import sysfrom PyQt4 import QtCore, QtGui, uicqtCreatorFile = "" # 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_())

One of the things to note is the third line:

1 qtCreatorFile ="" # Enter file here.

You need to fill in the address of the file you created earlier. This file will be loaded into the built-in function:

1 Ui_MainWindow, QtBaseClass =uic.loadUiType(qtCreatorFile)

Let's take a look at this code in general:

12345 if __name__ = = "__main__" :      app = qtgui.qapplication (sys.argv)      window = myapp ()      Code class= "Python Plain" >window.show ()      sys.exit (app.exec_ ())

This main program creates a new Qt Gui application. , each QT application can be configured via the command line, so parameters must be passed in sys.argv . But now we can't use this. Finally, we created a MyApp class that inherits from the Qt library and invokes the initialization function of the parent class:

12345 class MyApp(QtGui.QMainWindow, Ui_MainWindow):    def __init__(self):        QtGui.QMainWindow.__init__(self)        Ui_MainWindow.__init__(self)        self.setupUi(self)

You don't necessarily have to know the details of the code. You just have to continue to develop it on the basis of it.

Download pyqt_skeleton.py This file and rename it to pyqt_first.py . This is because we do not want to change to the source file. The first thing to do is to import our own XML file into the code, which contains our GUI information. Put the following line:

1 qtCreatorFile ="" # Enter file here.

Replaced by

1 qtCreatorFile ="tax_calc.ui"

This allows us to load our GUI files into memory. Now, the most critical component of our GUI is our button. Once we press this button, something magical happens. What's going to happen? This requires us to tell the code what to Calculate Tax do when the button is pressed. In the __init__ function, add the following:

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

What's the use of this piece of code? Remember when we named the button for calc_tax_button it? (This is the name of the button object, not the prompt string displayed on the button.) clickedis a built-in function that is automatically called when a button is clicked (it's amazing). All QT components have specific functions that you can view in detail via Google. The last part of this code is connect(self.CalculateTax) . This means that the button will be linked to a function called, so that the self.CalculateTax code will be called whenever the user presses the button.

We have not implemented this function yet. So let's start writing.

In the MyApp class, add another function. We need to look at the whole function before we get to the details of it:

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)

OK, let's analyze the above code in one line.

We're going to do two things now: Read the price and the tax rate, and then calculate the final price. All right, let's get started. Keep in mind that we're going to call these components by the name we set (this is why I let you not use the default generic name for example box1 , otherwise we'll be annoyed when we write the code).

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

price_box.toPlainText()is a built-in function that can read the values in the input box. By the way, although you will be able to remember these functions when you use them more, because their names are very canonical, you don't have to remember all these functions from the beginning. Every time I use a keyword like "Qt Textbox reading Data" from Google, I find the function I need.

The function reads a value of type string, so we need to convert it to an integer type and there is a price variable.

Then read the tax rate:

1 tax =(self.tax_rate.value())

The same value() is the function that reads the spinbox median value. Thanks to Google.

We have now got the above two values so that we can calculate our final price with a very tall mathematical formula:

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

We have created a string variable to store our final price. Because the final direct display on the app will be a string-type value:

1 self.results_window.setText(total_price_string)

In results_window , we call the setText() function, which displays the string of the final price we have calculated.

Finally run the program we wrote:

1 python pyqt_first.py

Well, this is a simple PyQt tutorial.

If you also want to experience more fun things, you can try to use a different component, but first of all, if you put too many components in your application, it may be a little laborious ...

About Lane

Use PYQT to write the first Python GUI program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.