14. python from beginner to proficient - GUI programming

Table of contents

Commonly used GUI frameworks

wxPython: more commonly used

PyQt6: more commonly used

Desperate

Flexx

Tkinter

Install PyQt5

To develop PyQt5 programs you need to install three modules:

Install

Installation command:

window installation:

PyCharm software installation:      

PyCharm software configures PyQt5 and code conversion tools    

Configure PyQt5

Configure the transcoding tool

Create windows using Qt Designer

There are three main types of windows in Qt Designer:

Create main window steps

PyQt5 signals and slots        

Signals are linked to PyQt5’s built-in slot function

The signal is linked to the specified slot function

Label: label control

Two ways to set text:

Two ways to set text alignment:

Set text wrapping display

Set up hyperlink

Set display picture

Get label text

LineEdit control: single line text box

Commonly used methods:

Commonly used signals:

TextEdit control: multi-line text box

Commonly used methods:

PushButton control: button

Commonly used methods:

Commonly used new models:

CheckBox: check box

Checkboxes have three states:

RadioButton: radio button

Commonly used methods:

Commonly used signals:

ComboBox: drop-down combo box

Commonly used methods:

Commonly used signals:


Three basic elements of GUI (graphical user interface): input, processing, and output

Commonly used GUI frameworks

  • wxPython: more commonly used

    Official website

    wxPython is an excellent GUI graphics library for Python language, allowing Python programmers to easily create a complete GUI user interface with full function keys.

    wxPython is also an open source software with excellent cross-platform capabilities, and can run on 32-bit windows, most Unix or Unix-like systems, and Macintosh OS X.

  • PyQt6: more commonly used

    Official website

    Qt is a GUI library written in c++, and PyQt is the python version of the Qt library, supporting cross-platform

  • Desperate

    Kivy is an open source toolkit that enables programs created using the same source code to run across platforms. This framework is event-driven and based on the main loop, making it ideal for developing games.

  • Flexx

    Flexx is a pure Python toolkit for creating GUI applications. It uses Web technology for interface rendering. You can use Flexx to create desktop applications, and you can also export an application to a standalone HTML document. Because it is developed using pure Python, Flexx is cross-platform.

Tkinter

   TKinter is the standard python interface for the Tk graphical user interface toolkit. Tk is a lightweight cross-platform graphical user interface (GUI development tool) and a built-in python module.

Disadvantages: The GUI interface is low in appearance, some controls are incomplete and the documentation is not very sound

Install PyQt5

To develop PyQt5 programs you need to install three modules:

        pyqt5

        pyqt5-tools (comes with English version UI editor)

        pyqt5designer (this package is the Chinese version of the UI editor and does not need to be installed)

Install

Installation command:

        pip install module name [-i mirror address]

            #Because the default mirror address points to foreign official websites, the network speed is very slow, so it is generally necessary to formulate a domestic mirror address

window installation:

        Enter cmd in the search box and right-click to open as administrator (due to the relatively high security of Windows, it is best to install as an administrator to prevent permission issues during installation)

        pip install pyqt5 pyqt5-tools pyqt5designer -i  https://pypi.tuna.tsinghua.edu.cn/simple  #This method takes effect in the whole system

PyCharm software installation:      

Note: The default installation on PyCharm software can only take effect in the project where it is located.

Before installation, you need to set the python mirror source address under the console package button

Install PyQt5

 

PyCharm software configures PyQt5 and code conversion tools    

Configure PyQt5

Open the file in the upper left corner of PyCharm → Settings window

        #D:\Python\Lib\site-packages directory contains all installed packages

        #$ProjectFileDir$: Project file directory

 

Configure the transcoding tool

  • In fact, it is to configure a python command to convert the designed ui file into python code:

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

                $ProjectFileDir$: Indicates the project path where the file is located.
                $FileDir$: Indicates the path where the file is located.
                $FileName$: represents the file name (without path).
                $FileNameWithoutExtension$: Represents the file name without extension.

  •  When using the conversion tool, first select the UI file to be converted and then click the configured conversion tool to automatically convert it into a .py file:

            The conversion command actually executed: D:\Python\python.exe -m PyQt5.uic.pyuic untitled.ui -o untitled.py

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

Create windows using Qt Designer

There are three main types of windows in Qt Designer:

        Main Window: The main window, which mainly provides users with a window with toolbar menu bar and status bar

        Widget: Universal window

        Dialog: dialog box, mainly used to perform some short-term tasks or interact with the user

Create main window steps

  1. Create main window
  2. Design main window
  3. Preview window effect
  4. View python code
  5. .ui converted to,py
  6. Run the main window: Write a program entry for the main window to run the main window

Example: main window python code

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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# 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_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(256, 250)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(130, 30, 91, 20))
        self.textEdit.setObjectName("textEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(70, 30, 54, 12))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(70, 70, 54, 12))
        self.label_2.setObjectName("label_2")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(130, 70, 91, 20))
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(90, 120, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 256, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "用户名"))
        self.label_2.setText(_translate("MainWindow", "密码"))
        self.pushButton.setText(_translate("MainWindow", "登录"))

if __name__ == '__main__':
   import sys
   app = QtWidgets.QApplication(sys.argv) #创建app对象
   MainWindow = QtWidgets.QMainWindow() # 创建窗体对象
   ui = Ui_MainWindow() # 创建PyQt设计的窗体对象
   ui.setupUi(MainWindow) # 调用PyQt窗体的方法对窗体对象进行初始化设置
   MainWindow.show() # 显示窗体
   sys.exit(app.exec_()) # 程序关闭时退出进程

PyQt5 signals and slots        

Signals and slots are the core mechanism of PyQt5 and the basis for communication between wires when programming PyQt5.

        PyQt5 requires connections between signals and slots to implement various operations

        In PyQt5, every QObject object supports the signal and slot mechanism.

        Signal: Equivalent to events, such as mouse events and keyboard events

        Slot: equivalent to function

The principle of signal and slot mechanism implementation:

        First the sender sends the signal to the receiver

        During the sending process, some protocols are required to connect, and the connection uses the connect() method

        After receiving the signal, the receiver needs to call the specified slot function to execute to realize the corresponding function

Signals are linked to PyQt5’s built-in slot function

Demo: Add a button and close the window by associating the built-in close() slot function when the button is clicked.

Finally, preview and save and convert it to a .py file to perform the test. The previous .py file with the same name will be overwritten during the conversion, and the program entry needs to be added again

code example 

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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# 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_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(559, 411)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(170, 110, 81, 41))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(170, 180, 51, 31))
        self.label_2.setObjectName("label_2")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(250, 110, 121, 41))
        self.textEdit.setObjectName("textEdit")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(250, 180, 121, 41))
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(210, 240, 111, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(220, 310, 91, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 559, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.pushButton_2.clicked.connect(MainWindow.close) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "账号"))
        self.label_2.setText(_translate("MainWindow", "密码"))
        self.pushButton.setText(_translate("MainWindow", "登陆"))
        self.pushButton_2.setText(_translate("MainWindow", "关闭"))

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()  # 创建窗体对象
    ui = Ui_MainWindow()  # 创建PyQt设计的窗体对象
    ui.setupUi(MainWindow)  # 调用PyQt窗体的方法对窗体对象进行初始化设置
    MainWindow.show()  # 显示窗体
    sys.exit(app.exec_())  # 程序关闭时退出进程

In the code, the performance is: self.pushButton_2.clicked.connect(MainWindow.close)

        #Indicates that the clicked signal of the pushButton button is linked to the close of the current window. Through this line of code, the current window is closed when the close button is clicked.

The signal is linked to the specified slot function

Note: When associating a slot function, you only need to write the name of the function. Do not write parentheses or pass parameters.

Code example: 

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

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# 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_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(559, 411)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(170, 110, 81, 41))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(170, 180, 51, 31))
        self.label_2.setObjectName("label_2")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(250, 110, 121, 41))
        self.textEdit.setObjectName("textEdit")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(250, 180, 121, 41))
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(210, 240, 111, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(220, 310, 91, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 559, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.pushButton_2.clicked.connect(self.showinfo) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "账号"))
        self.label_2.setText(_translate("MainWindow", "密码"))
        self.pushButton.setText(_translate("MainWindow", "登陆"))
        self.pushButton_2.setText(_translate("MainWindow", "关闭"))

    def showinfo(self):
        print("自定义槽函数")

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()  # 创建窗体对象
    ui = Ui_MainWindow()  # 创建PyQt设计的窗体对象
    ui.setupUi(MainWindow)  # 调用PyQt窗体的方法对窗体对象进行初始化设置
    MainWindow.show()  # 显示窗体
    sys.exit(app.exec_())  # 程序关闭时退出进程

Label: label control

Label control: Corresponds to the QLabel class in PyQt5, which is essentially an object of this class. Mainly used to display text that cannot be edited by the user, or to identify objects on the form

Most properties can be edited in the text property three-dot button in the property bar of QT's UI editor.

Two ways to set text:

        (1) Select the label in the QT UI editor, and then find the text attribute in the property bar on the right to edit it.

                        

        (2) Add self.label.setText() to the initialization function in the python code

Two ways to set text alignment:

(1) Select the label in the QT UI editor, and then find the alignment attribute in the property bar on the right to edit it.

(2) Add self.label.setAlignment() to the initialization function in the python code

 

Set text wrapping display

(1) Select the label in the QT UI editor, and then find the wordWrap attribute in the property bar on the right to edit it.

 (2) Add self.label.setWordWrap() to the initialization function in the python code

Set up hyperlink

(1) Select label in QT's UI editor, then find the Text property and OpenExternalLinks property in the property bar on the right for editing.

 

(2) Add setText() and setOpenExternalLinks() to the initialization function in the python code and use it in combination

Set display picture

Now put the image in the local project

In the initialization function in python code

First import from PyQt5.QtGui import QPixmap class

Add the self.label.setPixmap(QPixmap("tupian.gif")) method

Get label text

Add the text() method to the initialization function in the python code. After execution, the corresponding text will be obtained in the console (the picture needs to be commented out first)

Code example:

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

# Form implementation generated from reading ui file '5.1.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(376, 231)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(30, 30, 314, 81))
        self.label.setText("用户名:")

        # 设置文本对齐方式
        self.label.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)

        # 设置图片
        from PyQt5.QtGui import QPixmap # 导入QPixmap类
        self.label.setPixmap(QPixmap('test.png')) # 为label设置图片


        # # 设置长文本,并换行显示
        # self.label.setText("每天编程1小时,从菜鸟到大牛")
        # self.label.setWordWrap(True)

        self.label.setTextFormat(QtCore.Qt.AutoText)
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 336, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        print(self.label.text()) # 获取Label的文本

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


import sys
# 主方法,程序从此处启动PyQt设计的窗体
if __name__ == '__main__':
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow() # 创建窗体对象
   ui = Ui_MainWindow() # 创建PyQt设计的窗体对象
   ui.setupUi(MainWindow) # 调用PyQt窗体的方法对窗体对象进行初始化设置
   MainWindow.show() # 显示窗体
   sys.exit(app.exec_()) # 程序关闭时退出进程

LineEdit control: single line text box

LineEdit control: Corresponds to the QLineEdit class in PyQt5, which means that only a single line of text can be entered. Can be used in the window when entering account and password on some website login pages.

Commonly used methods:

        setText(): Set the content of the text box
        text(): Get the content of the text box

        setEchoMode(): There are four modes for setting the mode for displaying characters in the text box:

                Normal: Default mode, whatever is entered is displayed.

                Password: Password mode, usually covering the characters you enter with small black dots

                PasswordEchoOnEdit: Enter characters to display the input content when editing, otherwise it will be replaced by a small black dot

                NoEcho: No input is visible

        setAlignment(): Set the alignment of text

        setFocus(): Get mouse focus

        clear(): clear the text box

        setMaxLength(): Set the maximum length that the text box allows to enter

        setReadOnly(): Set whether it is read-only

        setValidator(): Set the text validator, restrict the text content to decimals, integers, numbers, etc. It can be specified in combination with regular expressions.

Commonly used signals:

textChanged: Emitted when the text box content is changing. For example, when you modify the quantity of a product purchased on Taobao, the total price will also change accordingly.

editingFinished: Emitted when the Enter key is pressed after editing

TextEdit control: multi-line text box

TextEdit: Corresponds to the QTextEdit class in PyQt5, which is mainly used to enter multi-line text content. When the text content exceeds the display range of the control, this control will automatically display a vertical scroll bar and support displaying HTML.

Commonly used methods:

setPlainText(): Set the content of the multi-line text box
toPlainText(): Get the content of the multi-line text box
setHtml(): Set the content of the html document
toHtml(): Get the content of the html document
clear(): Clear the content of the text box
setTextColor( ): Set the color of the text box
setWordWrapMode(): Set automatic line wrapping
setTextBackgroundColor(): Set the background color of the text

PushButton control: button

PushButton: Corresponds to the QPushButton class, which can display both text and images.

Commonly used methods:

setText(): Set the text to be displayed
setIcon(): Set the icon displayed on the button
setEnabled(): Set whether the button is available
setIconSize(): Set the icon size on the button
setShortcut(): Set the shortcut key for the button
text() : Get the text displayed by the button

Commonly used new models:

clicked: Indicates that the execution signal is emitted when the button is clicked

Example: A prompt box pops up when the login icon button is clicked, and closes the window when it is closed

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

# Form implementation generated from reading ui file '5.7.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap,QIcon


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(225, 121)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 83, 61, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setIcon(QIcon(QPixmap("login.ico"))) # 为登录按钮设置图标
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(29, 22, 54, 12))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(29, 52, 54, 12))
        self.label_2.setObjectName("label_2")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(79, 18, 113, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(78, 50, 113, 20))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)  # 设置文本框为密码
        self.lineEdit_2.setValidator(QtGui.QIntValidator(10000000, 99999999))  # 设置只能输入8位数字
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(120, 83, 61, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setIcon(QIcon(QPixmap("exit.ico")))  # 为退出按钮设置图标
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        # 为登录按钮的clicked信号绑定自定义槽函数
        self.pushButton.clicked.connect(self.login)
        # 为退出按钮的clicked信号绑定MainWindow窗口自带的close槽函数
        self.pushButton_2.clicked.connect(MainWindow.close)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def login(self):
        from PyQt5.QtWidgets import QMessageBox
        # 使用information()方法弹出信息提示框
        QMessageBox.information(MainWindow, "登录信息", "用户名:"+self.lineEdit.text()+"  密码:"+self.lineEdit_2.text(), QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
            _translate = QtCore.QCoreApplication.translate
            MainWindow.setWindowTitle(_translate("MainWindow", "系统登录"))
            self.pushButton.setText(_translate("MainWindow", "登录"))
            self.label.setText(_translate("MainWindow", "用户名:"))
            self.label_2.setText(_translate("MainWindow", "密  码:"))
            self.pushButton_2.setText(_translate("MainWindow", "退出"))

import sys
# 主方法,程序从此处启动PyQt设计的窗体
if __name__ == '__main__':
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow() # 创建窗体对象
   ui = Ui_MainWindow() # 创建PyQt设计的窗体对象
   ui.setupUi(MainWindow) # 调用PyQt窗体的方法对窗体对象进行初始化设置
   MainWindow.show() # 显示窗体
   sys.exit(app.exec_()) # 程序关闭时退出进程

CheckBox: check box

CheckBox: Corresponds to the QCheckBox class, indicating that multiple selections can be made. Usage scenarios: For example, when logging in with QQ, you can automatically log in and remember passwords; when setting database permissions, you can choose multiple permissions, etc.

Checkboxes have three states:

QT.Checked: selected

QT.Unchecked: unchecked

QT.PartiallyChecked: Half-selected state, only select some items among some items

     Note: By default, there is only selected or unselected state. If you need to have a semi-selected state, you need to set Tristate () for special settings, and you can use setTristate () to determine which state it is currently in.

Example: Click the Settings button to obtain the selected permissions

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

# Form implementation generated from reading ui file '5.11.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(211, 139)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(22, 19, 101, 16))
        self.checkBox.setObjectName("checkBox")
        self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_2.setGeometry(QtCore.QRect(122, 19, 101, 16))
        self.checkBox_2.setObjectName("checkBox_2")
        self.checkBox_3 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_3.setGeometry(QtCore.QRect(22, 49, 101, 16))
        self.checkBox_3.setObjectName("checkBox_3")
        self.checkBox_4 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_4.setGeometry(QtCore.QRect(122, 49, 101, 16))
        self.checkBox_4.setObjectName("checkBox_4")
        self.checkBox_5 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_5.setGeometry(QtCore.QRect(22, 78, 101, 16))
        self.checkBox_5.setObjectName("checkBox_5")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(120, 106, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.pushButton.clicked.connect(self.getvalue)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def getvalue(self):
        oper="" # 记录用户权限
        if self.checkBox.isChecked(): # 判断复选框是否选中
            oper+=self.checkBox.text() # 记录选中的权限
        if self.checkBox_2.isChecked():
            oper +='\n'+ self.checkBox_2.text()
        if self.checkBox_3.isChecked():
            oper+='\n'+ self.checkBox_3.text()
        if self.checkBox_4.isChecked():
            oper+='\n'+ self.checkBox_4.text()
        if self.checkBox_5.isChecked():
            oper+='\n'+ self.checkBox_5.text()
        from  PyQt5.QtWidgets import QMessageBox
        # 使用information()方法弹出信息提示,显示所有选择的权限
        QMessageBox.information(MainWindow, "提示", "您选择的权限如下:\n"+oper, QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "设置用户权限"))
        self.checkBox.setText(_translate("MainWindow", "基本信息管理"))
        self.checkBox_2.setText(_translate("MainWindow", "进货管理"))
        self.checkBox_3.setText(_translate("MainWindow", "销售管理"))
        self.checkBox_4.setText(_translate("MainWindow", "库存管理"))
        self.checkBox_5.setText(_translate("MainWindow", "系统管理"))
        self.pushButton.setText(_translate("MainWindow", "设置"))

import sys
# 主方法,程序从此处启动PyQt设计的窗体
if __name__ == '__main__':
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow() # 创建窗体对象
   ui = Ui_MainWindow() # 创建PyQt设计的窗体对象
   ui.setupUi(MainWindow) # 调用PyQt窗体的方法对窗体对象进行初始化设置
   MainWindow.show() # 显示窗体
   sys.exit(app.exec_()) # 程序关闭时退出进程

RadioButton: radio button

RadioButton: Corresponds to the QRadioButton class, such as radio-choice questions or radio-choice settings.

Commonly used methods:

setText(): Set the method to display the radio button

setChecked()/setCheckable(): Set whether the radio button is selected. True means it is selected.

isChecked(): Gets the current selected status of the radio button and returns True to indicate it is selected.

text(): Get the text displayed by the radio button

Commonly used signals:

clicked: Fired every time a radio button is clicked, regardless of state post changes

toggled: Emitted when the status changes

ComboBox: drop-down combo box

ComboBox: Corresponds to the QComboBox class, which is mainly used to display data in the drop-down combo box. For example, when selecting a language, the drop-down list displays various languages ​​to provide choices.

Commonly used methods:

addItem(): Add items
addItems(): Add multiple items at once
setItemText(): Set the text of the item
count(): Get the number of all options
currentText(): Get the text of the currently selected item
currentIndex(): Get the index of the current item
itemText(): Get the text whose index is the index item
clear(): Delete all options

Commonly used signals:

activated: Emitted when the drop-down option is selected
currentIndexChanged: Emitted when the index of the selected drop-down option changes

Example: Display the contents of the selected drop-down combo box in the label control

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

# Form implementation generated from reading ui file '5.12.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(244, 97)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(30, 20, 41, 16))
        self.label.setObjectName("label")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(70, 15, 141, 22))
        self.comboBox.setObjectName("comboBox")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(35, 56, 171, 16))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # 定义职位列表
        list=["总经理", "副总经理", "人事部经理", "财务部经理", "部门经理", "普通员工" ]
        self.comboBox.addItems(list) # 将职位列表添加到ComboBox下拉列表中
        # 将ComboBox控件的选项更改信号与自定义槽函数关联
        self.comboBox.currentIndexChanged.connect(self.showinfo)

    def showinfo(self):
        self.label_2.setText("您选择的职位是:"+self.comboBox.currentText()) # 显示选择的职位


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "职位:"))


import sys
# 主方法,程序从此处启动PyQt设计的窗体
if __name__ == '__main__':
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow() # 创建窗体对象
   ui = Ui_MainWindow() # 创建PyQt设计的窗体对象
   ui.setupUi(MainWindow) # 调用PyQt窗体的方法对窗体对象进行初始化设置
   MainWindow.show() # 显示窗体
   sys.exit(app.exec_()) # 程序关闭时退出进程

Guess you like

Origin blog.csdn.net/weixin_43812198/article/details/131367439