Introduction to Python PyQt5

Well, we open a new chapter, because I Gui design than other cooked a little, so I'll have to open a new pit design Gui. Explain here. We are using PyQt5, not Python comes with Tkinter. That I'm not that familiar, not to say basic. This column we are mainly talking about the foundation PyQt5, as for more, I think we find their own way, after all, difficult, and I'm tired, can not read write more. Well, the introduction to the column, now says the official.

First, because PyQt5 third-party libraries, if you direct import, it would be an error. You must download, download Python as to how third-party libraries, Python libraries on the basis of my column has already been said. All of you to read. (Or should I say a simple point of it ...)

At the command prompt / cmd in (Windows systems, Linux and Apple systems sorry I have not used, please understand.)
PIP install PyQt5

It is very simple, if error, you will see a lot of red, if the end is ... time out, it is interrupted, try more than once. Other self-discovery, after all, too much. I think the best .whl or download files.

So much nonsense, let's look at a practical tool I recently boring series, the interface is very simple, after all, I probably only made up less than a few hours.

import sys,sip
from PyQt5.QtWidgets import QApplication, QWidget,QLabel,QPushButton,QCheckBox, QComboBox,QLineEdit
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt

class Exchange_of_weather_degree_units(QWidget):

    def __init__(self):
        super().__init__()
        self.setting()

    def setting(self):
        self.unit = None

        self.choice = QComboBox(self)
        self.choice.addItem('℃')
        self.choice.addItem('℉')
        self.choice.activated[str].connect(self.choice_)
        self.choice.move(50,15)

        self.number = QLineEdit(self)
        self.number.setPlaceholderText('输入转化的数值')
        self.number.move(15,50)

        self.arrowhead = QLabel(self)
        self.arrowhead.setText('——————>')
        self.arrowhead.setFont(QFont('microsoft Yahei', 20))
        self.arrowhead.move(165,20)

        self.result = QLabel(self)
        self.result.setText('                         ')
        self.result.setFont(QFont('microsoft Yahei', 15))
        self.result.move(370, 27.5)

        self.yes = QPushButton('确定',self)
        self.yes.clicked.connect(self.yes_)
        self.yes.move(220,50)

        self.setGeometry(300, 100, 520, 100)
        self.setWindowTitle('摄氏度与华氏度的转换')
        self.show()

    def choice_(self,text):
        self.unit = text

    def yes_(self):
        try:
            if self.unit == '℃':
                result_ = eval(self.number.text()) * 1.8 + 32
                self.result.setText(str(result_) + '℉')

            if self.unit == '℉':
                result_ = round((eval(self.number.text()) - 32) / 1.8,6)
                self.result.setText(str(result_) + '℃')

            else:
                result_ = eval(self.number.text()) * 1.8 + 32
                self.result.setText(str(result_) + '℃')
        except:
            self.result.setText('请输入数字')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    Ex = Exchange_of_weather_degree_units()
    sys.exit(app.exec_())

This is a small conversion tool Fahrenheit and Celsius, for me, very practical. We do not understand, is copied in the past to see the effect just fine.

In fact, this inside knowledge involved is not much, so we do not be afraid. Because the most basic PyQt5 framework is this:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.settings()
    def settings(self):
        self.setGeometry(300, 300, 450, 350)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Of course, I think this is just the simplest model, in fact, it can be more streamlined than this. But length is almost the same. So please do not be afraid.

As for what Qt5 is that we search on their own, anyway, I can tell you that this is a very powerful and sophisticated library, Qt itself is actually a tool. If you want, you can add me QQ.

Speaking of that, we now have to analyze this skeleton code:

sys library is a standard library:

the role of the library sys: View python interpreter information and passes the information to the python interpreter.
sys.argv: get a list of command line arguments, the first element is the program itself
sys.exit (n): Exit Python program, exit (0) indicates a normal exit. When the parameter non-zero, raises a SystemExit exception, the exception may be captured in the program
sys.version: obtaining range-Python interpreter version information
sys.maxsize: Int maximum value, 64-bit platform is 2 ** 63--1
sys.path: return to the module search path, use the PYTHONPATH environment variable initialization value
sys.platform: returns the name of the operating system platform
sys.stdin: enter the relevant
sys.stdout: output related
sys.stderr: errors related
sys.exc_info () : return exception information tuple three yuan
sys.getdefaultencoding (): Get the current coding system, by default. 8-UTF
sys.setdefaultencoding (): set default encoding system
sys.getfilesystemencoding (): Get file system using the encoding mode is the default 8-UTF
sys.modules # returns all current Python module has been introduced into the environment in the form of a dictionary
sys.builtin_module_names: returns a list that contains all compiled into Python interpreter module name
sys.copyright: Python's current copyright information
sys.flags: command line identifies the list of status messages. Read-only.
sys.getrefcount (object): Returns the object's reference number
sys.getrecursionlimit (): returns a Python maximum depth of recursion, the default 1000
sys.getsizeof (Object [, default]): Returns the size of the object
sys.getswitchinterval (): returns the thread switching interval default 0.005 seconds
sys.setswitchinterval (interval): set the thread switching time interval in seconds
sys.getwindowsversion (): returns the current version information windwos system
sys.hash_info: returns default parameter Python hashing method
sys. implementation: concrete realization of the currently running Python interpreter, such as CPython
sys.thread_info: current thread information

These are some of my reference, but mainly to see PyQt5 library code itself, then English Dictionary results.

Then unpack, this is no problem now.

Then create Example library inherits QWidget.
PyQt5 have a lot of modules, which QWidget is a module that contains a series of desktop applications to create UI elements.

The following initialization code should be no problem.
Then comes the self.setGeometry (300, 300, 450, 350), this window is to set the distance to the top left corner of the screen and the length and width.
This change to change the data we understand.

Then self.show (), this interface is displayed.
Finally, run, if a judgment that it simply is this:
the other documents in the call if the code does not execute when your library.
Then app is the line that we all PyQt5 application must create an application (Application) object. sys.argv parameter is a list of parameters from the command line. Python scripts can be run in the shell. This is a way we are used to control our application started.

ex is calling the library, and then executed first __init__ code, then __init__ and call settings, so direct execution initUI in the program. The last exit.

Let us change the look better.

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.settings()
        
    def setting(self):
    	self.setWindowTitle(sys.argv[0])
        #self.setWindowIcon(QIcon('图片名.ico')) 自己加图片
        self.setGeometry(300, 300, 450, 350)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

We added two lines, the first line in the settings of, is to set the title. The second line all of you to add ico pictures, which would be more enriched. This way I will not list here, we all remember just fine.

Well, this is today's Gui knowledge, if you like, might spend five seconds, plus followers, a point like this. If you have doubts, you can ask in the comments area, partners can also add my QQ: 3418772261. I will give you a lot of Python resources. Q & A can also be provided. So the next issue goodbye, bye!

Published 20 original articles · won praise 66 · views 20000 +

Guess you like

Origin blog.csdn.net/Persia_king/article/details/105197457