search
HomeBackend DevelopmentPython TutorialDetailed tutorial for using PyQt5 in python (code example)

This article brings you a detailed tutorial (code example) on using PyQt5 in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

One: Install PyQt5

pip install pyqt5

Two: Simple use of PyQt5

1: Use PyQt5 to create a simple window

import sys
from PyQt5 import QtWidgets
#创建一个应用(Application)对象,sys.argv参数是一个来自命令行的参数列表,
# Python脚本可以在shell中运行。这是我们用来控制我们应用启动的一种方法。
app = QtWidgets.QApplication(sys.argv)
#创建一个widget组件基础类
windows = QtWidgets.QWidget()
#设置widget组件的大小(w,h)
windows.resize(500,500)
#设置widget组件的位置(x,y)
windows.move(100,100)
"""
#设置widget组件的位置居中
qr = windows.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
windows.move(qr.topLeft())
"""
#等同于 w.resize(500,500)和w.move(100,100)两句结合,(x,y,w,h)
#windows.setGeometry(100,100,500,500)
#show()方法在屏幕上显示出widget组件
windows.show()
#循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过
sys.exit(app.exec_())

The phenomenon is as follows:

Detailed tutorial for using PyQt5 in python (code example)

2: Add a title and icon to the created window

import sys
from PyQt5 import QtWidgets,QtGui
#创建一个应用(Application)对象,sys.argv参数是一个来自命令行的参数列表,
# Python脚本可以在shell中运行。这是我们用来控制我们应用启动的一种方法。
app = QtWidgets.QApplication(sys.argv)
#创建一个widget组件基础类
windows = QtWidgets.QWidget()
#设置widget组件的大小(w,h)
windows.resize(500,500)
#设置widget组件的位置(x,y)
windows.move(100,100)
"""
#设置widget组件的位置居中
qr = windows.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
windows.move(qr.topLeft())
"""
#等同于 w.resize(500,500)和w.move(100,100)两句结合,(x,y,w,h)
#windows.setGeometry(100,100,500,500)
#给widget组件设置标题
windows.setWindowTitle('标题')
#给widget组件设置图标
windows.setWindowIcon(QtGui.QIcon('2.png'))
#show()方法在屏幕上显示出widget组件
windows.show()
#循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过
sys.exit(app.exec_())

The phenomenon is as follows:

Detailed tutorial for using PyQt5 in python (code example)

3: Add a title and icon to the created window The window setting button and setting prompt

import sys
from PyQt5 import QtWidgets,QtGui
#创建一个应用(Application)对象,sys.argv参数是一个来自命令行的参数列表,
# Python脚本可以在shell中运行。这是我们用来控制我们应用启动的一种方法。
app = QtWidgets.QApplication(sys.argv)
#创建一个widget组件基础类
windows = QtWidgets.QWidget()
#设置widget组件的大小(w,h)
windows.resize(500,500)
#设置widget组件的位置(x,y)
windows.move(100,100)
"""
#设置widget组件的位置居中
qr = windows.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
windows.move(qr.topLeft())
"""
#等同于 w.resize(500,500)和w.move(100,100)两句结合,(x,y,w,h)
#windows.setGeometry(100,100,500,500)
#给widget组件设置标题
windows.setWindowTitle('标题')
#给widget组件设置图标
windows.setWindowIcon(QtGui.QIcon('2.png'))
#设置提示语的字体和大小
QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
#给widget组件设置提示语
windows.setToolTip('这是窗口提示')
#设置按钮并给按钮命名
btn = QtWidgets.QPushButton('button',windows)
#给按钮设置位置(x,y,w,h)
btn.setGeometry(200,200,100,50)
#给按钮设置提示语
btn.setToolTip('这是按钮提示')
#设置按钮样式
btn.setStyleSheet("background-color: rgb(164, 185, 255);"
        "border-color: rgb(170, 150, 163);"
        "font: 75 12pt \"Arial Narrow\";"
        "color: rgb(126, 255, 46);")
#点击按钮关闭创建的窗口
btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
#show()方法在屏幕上显示出widget组件
windows.show()
#循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过
sys.exit(app.exec_())

The phenomenon is as follows (click the button button, the window closes):

Detailed tutorial for using PyQt5 in python (code example)

4: Set label information

import sys
from PyQt5 import QtWidgets,QtGui,QtCore
#创建一个应用(Application)对象,sys.argv参数是一个来自命令行的参数列表,
# Python脚本可以在shell中运行。这是我们用来控制我们应用启动的一种方法。
app = QtWidgets.QApplication(sys.argv)
#创建一个widget组件基础类
windows = QtWidgets.QWidget()
#设置widget组件的大小(w,h)
windows.resize(500,500)
#设置widget组件的位置(x,y)
windows.move(100,100)
"""
#设置widget组件的位置居中
qr = windows.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
windows.move(qr.topLeft())
"""
#等同于 w.resize(500,500)和w.move(100,100)两句结合,(x,y,w,h)
#windows.setGeometry(100,100,500,500)
#给widget组件设置标题
windows.setWindowTitle('标题')
#给widget组件设置图标
windows.setWindowIcon(QtGui.QIcon('2.png'))
#设置lable信息
label = QtWidgets.QLabel(windows)
label.setGeometry(QtCore.QRect(100, 10, 100, 60))
label.setText('这是lable信息')
label.setObjectName('label')
#show()方法在屏幕上显示出widget组件
windows.show()
#循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过
sys.exit(app.exec_())

The phenomenon is as follows:

Detailed tutorial for using PyQt5 in python (code example)

##5: Configuration input box

import sys
from PyQt5 import QtWidgets,QtGui,QtCore,Qt
#创建一个应用(Application)对象,sys.argv参数是一个来自命令行的参数列表,
# Python脚本可以在shell中运行。这是我们用来控制我们应用启动的一种方法。
app = QtWidgets.QApplication(sys.argv)
#创建一个widget组件基础类
windows = QtWidgets.QWidget()
#设置widget组件的大小(w,h)
windows.resize(500,500)
#设置widget组件的位置(x,y)
windows.move(100,100)
"""
#设置widget组件的位置居中
qr = windows.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
windows.move(qr.topLeft())
"""
#等同于 w.resize(500,500)和w.move(100,100)两句结合,(x,y,w,h)
#windows.setGeometry(100,100,500,500)
#给widget组件设置标题
windows.setWindowTitle('标题')
#给widget组件设置图标
windows.setWindowIcon(QtGui.QIcon('2.png'))
#设置输入框
textbox = Qt.QLineEdit(windows)
textbox.resize(100,20)
textbox.move(50,50)
#show()方法在屏幕上显示出widget组件
windows.show()
#循环执行窗口触发事件,结束后不留垃圾的退出,不添加的话新建的widget组件就会一闪而过
sys.exit(app.exec_())
The phenomenon is as follows:

Detailed tutorial for using PyQt5 in python (code example)

3: Summarize the above method to implement a simple function, as follows:

The function is: after entering the value in the input box, click the button to print out the value you entered, and there will be a prompt when closing the window

import sys
from PyQt5 import QtWidgets,QtGui,QtCore,Qt
class GUI(QtWidgets.QWidget):
    def __init__(self):
        #初始化————init__
        super().__init__()
        self.initGUI()
    def initGUI(self):
        #设置窗口大小
        self.resize(500,500)
        #设置窗口位置(下面配置的是居于屏幕中间)
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        #设置窗口标题和图标
        self.setWindowTitle('窗口标题')
        self.setWindowIcon(QtGui.QIcon('2.png'))
        #设置窗口提示
        self.setToolTip('窗口提示')
        #设置label信息
        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(100, 10, 100, 60))
        self.label.setText('这是lable信息')
        self.label.setObjectName('label')
        # 设置label提示
        self.label.setToolTip('label提示')
        #设置输入框
        self.textbox = Qt.QLineEdit(self)
        self.textbox.resize(100, 20)
        self.textbox.move(100, 50)
        # 设置输入框提示
        self.textbox.setToolTip('输入框提示')
        #设置按钮
        self.btn =QtWidgets.QPushButton('按钮',self)
        self.btn.resize(100,20)
        self.btn.move(200,50)
        # 设置按钮样式
        self.btn.setStyleSheet("background-color: rgb(164, 185, 255);"
                          "border-color: rgb(170, 150, 163);"
                          "font: 75 12pt \"Arial Narrow\";"
                          "color: rgb(126, 255, 46);")
        # 设置按钮提示
        self.btn.setToolTip('按钮提示')
        #点击鼠标触发事件
        self.btn.clicked.connect(self.clickbtn)
        #展示窗口
        self.show();
    #点击鼠标触发函数
    def clickbtn(self):
        #打印出输入框的信息
        textboxValue = self.textbox.text()
        QtWidgets.QMessageBox.question(self, "信息", '你输入的输入框内容为:' + textboxValue,QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
        #清空输入框信息
        self.textbox.setText('')
    #关闭窗口事件重写
    def closeEvent(self, QCloseEvent):
        reply = QtWidgets.QMessageBox.question(self, '警告',"确定关闭当前窗口?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
            QCloseEvent.accept()
        else:
            QCloseEvent.ignore()
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    gui = GUI()
    sys.exit(app.exec_())
The phenomenon is:


Detailed tutorial for using PyQt5 in python (code example)

The above is the detailed content of Detailed tutorial for using PyQt5 in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools