Super full! Python graphical interface framework PyQt5 usage guide!

There are not many softwares that use Python to develop graphical interfaces. Compared with GUI interfaces, web-based applications may be more popular. But for people like me who are not familiar with other programming languages ​​​​such as C# or WPF, it may not be a good tool.

Common GUI Frameworks

  • PyQt5: Qt is a cross-platform C++ graphical user interface library. QT was once owned by Nokia and later sold to Digia Oyj, a Finnish software company. PyQt5 is a Python interface based on Digia's Qt5, which consists of a set of Python modules. PyQt5 itself has more than 620 classes and 6000 functions and methods. It can run on multiple platforms, including: Unix, Windows, and Mac OS.
  • Pyside6: Pyside is the Python package officially provided by QT company. The previous version was Pyside2, which corresponds to QT5. The naming rules of the latest version have been adjusted and changed to Pyside6, which corresponds to the QT6 version. Since the official product is more optimistic, the disadvantage is that the release is relatively late, and the information on the Internet is not as much as PyQt5.
  • Tkinter: Python's built-in GUI framework, implemented using TCL, and the TCL interpreter is embedded in Python. When using it, there is no need to install additional extension packages, and it can be directly imported and cross-platform. The disadvantage is that the UI layout is all implemented by code, and there are only 15 commonly used components, and the display effect is simple.
  • PySimpleGUI: PySimpleGUI is a wrapper around Tkinter. Implementing a custom GUI using PySimpleGUI requires much less code than writing the same GUI directly using Tkinter.
  • WxPython: wxPython is a binding of the Python language to the popular wxWidgets cross-platform GUI tool library. It is widely used, cross-platform, written in C++, and has few documents. Users may need to make some adjustments to the GUI code in different platforms according to the programming content. It is not easy to solve the problem, the code layout control is not intuitive.
  • Wax: Based on wxPython, a package made to overcome the problems of wxPython.
  • Kivy: mainly for multi-touch programs, smart phones and tablets, etc., and can also be used on systems without touch screen functions, full platform support (Windows, Linux, Mac OS X, Android and iOS.) written in Python and cython, Chinese The support is poor, you need to download the Chinese library and make the path yourself.
  • BeeWare: Write once. Deploy everywhere. Need to work with Kivy.
  • Toga: A GUI toolkit for native APP development using Python. Toga consists of a base component library with a shared interface to simplify platform-independent GUI development. Toga is available for Mac OS, Windows, Linux (GTK), and mobile platforms such as Android and iOS.
  • Eel: A lightweight Python library for making simple Electron-like (but lighter-weight) offline HTML/JS GUI applications with full access to Python capabilities and libraries.
  • Flexx: A pure Python toolkit for creating GUI applications. It uses web technology for rendering of the interface. You can use Flexx to create desktop applications, and you can also export an application to a stand-alone HTML document. Because it is developed in pure Python, Flexx is cross-platform. All you need is Python and a browser to run.
  • pywebview is a lightweight cross-platform wrapper around the webview component that allows displaying HTML content in its own native GUI window. It lets you use web technologies in your desktop applications while hiding as much as possible the fact that you use a browser to build your GUI.
  • enaml: A Python framework that allows you to achieve high-quality GUI interfaces with minimal effort, and a unique programming language. enaml combines a declarative language with a constraint-based layout system, allowing users to easily define flexible-layout UIs. enaml applications can run on any platform that supports Python and Qt.

Personal thoughts: Too much to learn, learn PyQt5 first, the reason is that there is a lot of information, and then learn pyside6 if you have enough energy to learn, and finally look at PySimpleGUI to see if you can solve some simple problems.

Introduction to PyQt5

PyQt is the Python language implementation of the Qt framework, developed by Riverbank Computing, and is one of the most powerful GUI libraries. PyQt provides a well-designed collection of window controls, and each PyQt control corresponds to a Qt control, so the API interface of PyQt is very close to that of Qt, but PyQt no longer uses the QMake system and Q_OBJECT macro.

PyQt5 provides GPL version and commercial version certificates. Free developers can use the free GPL license. If you need to use PyQt for commercial applications, you must purchase a commercial license.

PyQt5 features are as follows:

  • A high-performance Qt-based GUI control set.
  • It can run on Linux, Window and Mac OS systems across platforms.
  • Use the signal-slot mechanism for communication.
  • Fully encapsulate the Qt library.
  • You can use a mature IDE for interface design and automatically generate executable Python code.
  • Provides a complete set of window controls of all kinds.
  • PyQt5 is composed of a series of Python modules, with more than 620 classes, 6000 functions and methods, the main modules are as follows:
  • QtCore: Contains core non-GUI functions. Mainly works with time, files and folders, various data, streams, URLs, mime-like files, processes and threads.
  • QtGui: Contains window system, event handling, 2D images, basic painting, fonts and text classes.
  • QtWidgets: Contains a series of UI elements for creating desktop applications.
  • QtMultimedia: Contains classes that handle multimedia content and call the camera API.
  • QtBluetooth: Contains classes for finding and connecting to Bluetooth.
  • QtNetwork: Contains classes for network programming, these tools make TCP/IP and UDP development more convenient and reliable.
  • QtPositioning: Contains classes for positioning, using satellite, WiFi and even text.
  • Enginio: Contains classes for entering and managing Qt Cloud through the client.
  • QtWebSockets: Contains classes for the WebSocket protocol.
  • QtWebKit: Contains a WebKit2-based web browser.
  • QtWebKitWidgets: Contains the classes of WebKit1 based on QtWidgets.
  • QtXml: Contains classes for processing xml, and provides tools for SAX and DOM API.
  • QtSvg: Provides a class for displaying SVG content. Scalable Vector Graphics (SVG) is a graphic format based on Extensible Markup Language (XML) for describing two-dimensional vector graphics (this sentence comes from Wikipedia) .
  • QtSql: Provides tools for working with databases.
  • QtTest: Provides tools for testing PyQt5 applications.

Installation of PyQt5

Since fbs will be used for packaging in the later stage, fbs may have compatibility issues with versions later than Python 3.7, so I chose Python 3.6.8 to build the entire environment. The main content is: Python + PyCharm + PyQt5

Install PyQt5

pip install pyqt5

pip install pyqt5-tools

Among them, pyqt5-tools is a drag-and-drop interface design tool for Qt Designer. The following error may be reported during the installation process:

qt5-tools 5.15.2.1.2 has requirement click~=7.0, but you'll have click 8.0.1 which is incompatible.

solution:

pip install click~=7.0

Configuration of Qt Designer

Qt Designer is to place controls by dragging and dropping, and view the effects of controls in real time for quick UI design.

The composition of the whole screen:

  • The "Widget Box" on the left is a variety of components that can be dragged freely
  • The middle "MainWindow - untitled" form is the canvas
  • The "Object Inspector" on the upper right can view the structure of the current ui
  • The "Property Editor" in the middle of the right can set the properties of the currently selected component
  • The "Resource Browser" at the bottom right can add various materials, such as pictures, backgrounds, etc.

Finally, a .ui file (essentially a file in XML format) is generated, which can be used directly or converted into a .py file by the pyuic5 tool.

QtDesigner configuration

In Pycharm, open File – Settings – Tools – External Tools in turn, click + Create Tool, and configure as follows:

Name: QtDisigner

Program : D:\Program Files\Python36\Lib\site-packages\qt5_applications\Qt\bin\designer.exe # 请根据实际修改

Working directory: $FileDir$

PyUIC configuration

PyUIC mainly replaces the .ui files generated by Qt Designer with .py files.

In Pycharm, open File – Settings – Tools – External Tools in turn, click + Create Tool, and configure as follows:

Name: PyUIC

Program : D:\Program Files\Python36\python.exe # 当前Python目录,请根据实际修改

Arguments: -m PyQt5.uic.pyuic $FileName$ -o $FileNameWithoutExtension$.py

Working directory: $FileDir$

PyRCC configuration

PyRCC mainly replaces the written .qrc resource file with a .py file. In Pycharm, open File – Settings – Tools – External Tools in turn, click + Create Tool, and configure as follows:

Name: PyRCC

Program: D:\Program Files\Python36\pyrcc5.exe # 当前rcc工具目录,请根据实际修改

Arguments: $FileName$ -o $FileNameWithoutExtension$_rc.py

Working directory: $FileDir$

Example of using PyQt5

Create a blank interface:

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)

win = QMainWindow()

win.setGeometry(400, 400, 400, 300)

win.setWindowTitle("Pyqt5 Tutorial")

win.show()

sys.exit(app.exec_())

in:

  • Qapplication(): Each GUI must contain a Qapplication, and argv means to get the command line parameters. If you don't need to get it, you can use [] instead.
  • QMainWindow(): Similar to a container (window) used to contain widgets such as buttons, text, and input boxes. The arg flag can get the parameters when the command line is executed.
  • SetGeometry is used to define the size of the QMainWindow() window, syntax: setGeometry(x, y, width, height), where x, y are coordinate points on the screen.
  • show(): used to display the window
  • exit(app.exec_()): Set the window to run all the time and guide you to use the close button to close

Common Widgets supported by PyQt5 are:

From top to bottom, from left to right: Qlabel, QcomboBox, QcheckBox, QradioButton, QpushButton, QtableWidget, QlineEdit, Qslider, QProgressBar

For setting text content with Pyqt5 we use Qlabel:

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)

win = QMainWindow()

win.setGeometry(400, 400, 400, 300)

win.setWindowTitle("Pyqt5 Tutorial")

# Label Text

label = QLabel(win)

label.resize(200, 100)

label.setText("Hi this is Pyqt5")

label.move(100, 100)

win.show()

sys.exit(app.exec_())

Buttons and events:

import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton

def click():

    print("Hy Button is clicked!")

app = QApplication(sys.argv)

win = QMainWindow()

win.setGeometry(400, 400, 400, 300)

win.setWindowTitle("Pyqt5 Tutorial")

# Button

button = QPushButton(win)

button.resize(200, 100)

button.setText("Hi! Click Me")

button.move(100, 100)

button.clicked.connect(click)

win.show()

sys.exit(app.exec_())

button.clicked.connect() executes a specific event after the button is clicked.

PyQt5 combat

Practical project: simple weather query software

1. Use Qt Designer to design an interface

The controls used are Button, GroupBox, Label, ComboBox, and TextEdit, and two buttons queryBtn and clearBtn are defined at the same time, which are used to query and clear the weather data respectively. We need to bind the slot function as follows:

  • Select the signal/slot editor in the lower right corner of Qt Designer, click the + sign to add
  • Select queryBtn and clearBtn respectively, select signal clicked(), receiver Dialog and slot accept(), (I don’t know how to define the slot function here, and modify it later in the code)

After the above is completed, save it as a Weather.ui file.

2. Convert .ui file to .py file

PyQt5 supports direct use of .ui files:

import sys

from PyQt5 import QtWidgets, uic

app = QtWidgets.QApplication(sys.argv)

window = uic.loadUi("mainwindow.ui")

window.show()

app.exec()

But in order to better customize and modify the above slot function, you can use External Tools – PyUIC to generate Weather.py, the actual running command is as follows:

D:\Program Files\Python36\python.exe -m PyQt5.uic.pyuic Weather.ui -o Weather.py

Among them, we need to bind the slot function of the two buttons:

# self.queryBtn.clicked.connect(Dialog.accept)

# self.clearBtn.clicked.connect(Dialog.accept)

# 修改为:

self.queryBtn.clicked.connect(Dialog.queryWeather)

self.clearBtn.clicked.connect(Dialog.clearText)

The final Weather.py content is as follows:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Weather.ui'

#

# Created by: PyQt5 UI code generator 5.15.4

#

# WARNING: Any manual changes made to this file will be lost when pyuic5 is

# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):

    def setupUi(self, Dialog):

        Dialog.setObjectName("Dialog")

        Dialog.resize(600, 600)

        self.groupBox = QtWidgets.QGroupBox(Dialog)

        self.groupBox.setGeometry(QtCore.QRect(30, 20, 551, 511))

        self.groupBox.setObjectName("groupBox")

        self.label_2 = QtWidgets.QLabel(self.groupBox)

        self.label_2.setGeometry(QtCore.QRect(20, 30, 31, 16))

        self.label_2.setObjectName("label_2")

        self.comboBox = QtWidgets.QComboBox(self.groupBox)

        self.comboBox.setGeometry(QtCore.QRect(70, 30, 87, 22))

        self.comboBox.setObjectName("comboBox")

        self.comboBox.addItem("")

        self.comboBox.addItem("")

        self.comboBox.addItem("")

        self.textEdit = QtWidgets.QTextEdit(self.groupBox)

        self.textEdit.setGeometry(QtCore.QRect(20, 70, 491, 411))

        self.textEdit.setObjectName("textEdit")

        self.queryBtn = QtWidgets.QPushButton(Dialog)

        self.queryBtn.setGeometry(QtCore.QRect(490, 560, 93, 28))

        self.queryBtn.setObjectName("queryBtn")

        self.clearBtn = QtWidgets.QPushButton(Dialog)

        self.clearBtn.setGeometry(QtCore.QRect(30, 560, 93, 28))

        self.clearBtn.setObjectName("clearBtn")

        self.retranslateUi(Dialog)

        self.clearBtn.clicked.connect(Dialog.clearText)

        self.queryBtn.clicked.connect(Dialog.queryWeather)

        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):

        _translate = QtCore.QCoreApplication.translate

        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

        self.groupBox.setTitle(_translate("Dialog", "城市天气预报"))

        self.label_2.setText(_translate("Dialog", "城市"))

        self.comboBox.setItemText(0, _translate("Dialog", "北京"))

        self.comboBox.setItemText(1, _translate("Dialog", "苏州"))

        self.comboBox.setItemText(2, _translate("Dialog", "上海"))

        self.queryBtn.setText(_translate("Dialog", "查询"))

        self.clearBtn.setText(_translate("Dialog", "清空"))

3. Call MainDialog

Call the interface class Ui_Dialog in MainDialog, and then add the business logic code for querying the weather, so that the interface display and business logic are separated. Add a new demo.py file, and define two slot functions queryWeather() and clearText() in the MainDialog class, so that the two buttons (queryBtn and clearBtn) defined in the interface file Weather.ui can trigger the clicked signal and these two Slot functions are bound.

The complete code is as follows:

import sys

import Weather

from PyQt5.QtWidgets import QApplication, QDialog

import requests

class MainDialog(QDialog):

    def __init__(self, parent=None):

        super(QDialog, self).__init__(parent)

        self.ui = Weather.Ui_Dialog()

        self.ui.setupUi(self)

    def queryWeather(self):

        cityName = self.ui.comboBox.currentText()

        cityCode = self.getCode(cityName)

        r = requests.get(

            "https://restapi.amap.com/v3/weather/weatherInfo?key=f4fd5b287b6d7d51a3c60fee24e42002&city={}".format(

                cityCode))

        if r.status_code == 200:

            data = r.json()['lives'][0]

            weatherMsg = '城市:{}\n天气:{}\n温度:{}\n风向:{}\n风力:{}\n湿度:{}\n发布时间:{}\n'.format(

                data['city'],

                data['weather'],

                data['temperature'],

                data['winddirection'],

                data['windpower'],

                data['humidity'],

                data['reporttime'],

            )

        else:

            weatherMsg = '天气查询失败,请稍后再试!'

        self.ui.textEdit.setText(weatherMsg)

    def getCode(self, cityName):

        cityDict = {"北京": "110000",

                    "苏州": "320500",

                    "上海": "310000"}

        **return** cityDict.get(cityName, '101010100')

    def clearText(self):

        self.ui.textEdit.clear()

if __name__ == '__main__':

    myapp = QApplication(sys.argv)

    myDlg = MainDialog()

    myDlg.show()

    sys.exit(myapp.exec_())

The effect after running demo.py and executing the query:

4. Package the code into an exe file

Packaging .py files into executable exe is called freezing in Python. Commonly used tools include: PyInstaller, py2exe, cx_Freeze, bbfreze, py2app, etc. Function comparison:

  • py2exe: Software update is no longer active, so it is skipped.
  • pyinstaller: clearly supports win8, win10, theoretically supports win7, supports apple Macos, linux. pyinsaller can be packaged in the form of a folder containing the exe entry execution file, or it can be a separate exe file.
  • fbs: Based on PyInstaller, it is more convenient to use

Here fbs is selected for packaging. How to install fbs:

pip install fbs

To use, enter on the command line:

fbs startproject

After the execution is completed, you need to enter the name of some APPs, etc. After completion, the following directory will be generated:

Drag the PyQt5 code (demo.py and Weather.py) just written to the src/main/python folder, delete the original main.py, and modify demo.py to main.py. Then open main.py and add the following code at the top of the file:

from fbs_runtime.application_context.PyQt5 import ApplicationContext
```
完成后执行:
```
fbs freeze
```
即可实现打包。生成的exe可执行文件在\target\MyApp文件下。

Digression

In this first year of fast-growing technology, programming is like a ticket to a world of infinite possibilities for many people. In the star lineup of programming languages, Python is like the leading superstar. With its concise and easy-to-understand syntax and powerful functions, it stands out and becomes one of the most popular programming languages ​​in the world.


The rapid rise of Python is extremely beneficial to the entire industry , but " 人红是非多" has caused it to add a lot of criticism, but it still cannot stop its hot development momentum.

Will Python remain relevant and intact for the rest of the next decade? Today, we're going to analyze the facts and dispel some misconceptions.

If you are interested in Python and want to get a higher salary by learning Python, then the following set of Python learning materials must be useful to you!

Materials include: Python installation package + activation code, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other learning tutorials. Even beginners with 0 basics can understand and understand. Follow the tutorial and take you to learn Python systematically from zero basics!

1. Learning routes in all directions of Python

The route of all directions in Python is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.
insert image description here
2. Python learning software

If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here!
insert image description here
3. Python introductory learning video

There are also many learning videos suitable for getting started with 0 basics. With these videos, you can easily get started with Python~insert image description here

4. Python exercises

After each video lesson, there are corresponding practice questions, you can test the learning results haha!
insert image description here

Five, Python actual combat case

Optical theory is useless. You have to learn to type codes along with it, and then you can apply what you have learned in practice. At this time, you can learn from some practical cases. This information is also included~insert image description here

6. Python interview materials

After we have learned Python, we can go out and find a job with the skills! The following interview questions are all from first-line Internet companies such as Alibaba, Tencent, and Byte, and some Alibaba bosses have given authoritative answers. After reading this set of interview materials, I believe everyone can find a satisfactory job.
insert image description here
insert image description here
7. Information collection

The full set of learning materials for the above-mentioned full version of Python has been uploaded to the CSDN official website. Those who need it can scan the QR code of the CSDN official certification below on WeChat to receive it for free.

Guess you like

Origin blog.csdn.net/Python966/article/details/132209882