[ PyQt入门教程 ] PyQt5基本控件使用:消息弹出、用户输入、文件对话框

简介: [ PyQt入门教程 ] PyQt5基本控件使用:消息弹出、用户输入、文件对话框 本文主要介绍PyQt界面实现中常用的消息弹出对话框、提供用户输入的输入框、打开文件获取文件/目录路径的文件对话框。

[ PyQt入门教程 ] PyQt5基本控件使用:消息弹出、用户输入、文件对话框
本文主要介绍PyQt界面实现中常用的消息弹出对话框、提供用户输入的输入框、打开文件获取文件/目录路径的文件对话框。学习这三种控件前,先想一下它们使用的主要场景:

1、消息弹出对话框。程序遇到问题需要退出需要弹出错误提示框 、程序执行可能造成的风险需要弹出警告窗口提示用户是否进一步执行等等。

2、用户输入框。比如常见的让用户选择执行的程序分支、yes/no等等。

3、文件对话框。获取本地文件或者文件夹的完整路径甚至是直接打开文件显示文件内容。

本文主要针对这三种控件的主要场景进行介绍。

QMessageBox:弹出对话框控件
QMessageBox是一种通用的弹出式对话框,用于显示消息,允许用户通过单击不同的标准按钮对消息进行反馈。弹出式对话框有很多类型,如提示、警告、错误、询问、关于等对话框。这些不同类型的QMessageBox对话框只是显示时图标不同,其他功能一样。

QMessageBox类中常用方法

information(QWdiget parent,title,text,buttons,defaultButton):弹出消息对话框。

question(QWidget parent,title,text,buttons,defaultButton):弹出问答对话框

warning(QWidget parent,title,text,buttons,defaultButton):弹出警告对话框

critical(QWidget parent,title,text,buttons,defaultButton):弹出严重错误对话框

about(QWidget parent,title,text):弹出关于对话

参数解释如下:

parent:指定的父窗口控件。

title:表示对话框标题。

text:表示对话框文本。

buttons:表示多个标准按钮,默认为ok按钮。

defaultButton表示默认选中的标准按钮,默认选中第一个标准按钮。

其他方法如下:

setTitle():设置标题

setText():设置正文消息

setIcon():设置弹出对话框的图片

QMessageBox的标准按钮类型

QMessage.Ok 同意操作、QMessage.Cancel  取消操作、QMessage.Yes  同意操作、QMessage.No  取消操作、QMessage.Abort  终止操作、QMessage.Retry 重试操作、QMessage.Ignore  忽略操作

5种常用的消息对话框及其显示效果

(1)消息对话框,用来告诉用户关于提示信息

QMessageBox.information(self, '信息提示对话框','前方右拐到达目的地',QMessageBox.Yes | QMessageBox.No) 

(2)提问对话框,用来告诉用户关于提问消息。

QMessageBox.question(self, "提问对话框", "你要继续搞测试吗?", QMessageBox.Yes | QMessageBox.No)

(3)警告对话框,用来告诉用户关于不寻常的错误消息。

QMessageBox.warning(self, "警告对话框", "继续执行会导致系统重启,你确定要继续?", QMessageBox.Yes | QMessageBox.No)

(4)严重错误对话框,用来告诉用户关于严重的错误消息。

QMessageBox.critical(self, "严重错误对话框", "数组越界,程序异常退出", QMessageBox.Yes | QMessageBox.No)

(5)关于对话框

QMessageBox.about(self, "关于对话框", "你的Windows系统是DOS1.0")

上述程序完整代码如下:

复制代码

-- coding: utf-8 --

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

class Ui_Form(object):

def setupUi(self, Form):
    Form.setObjectName("Form")
    Form.resize(431, 166)
    self.pushButton = QtWidgets.QPushButton(Form)
    self.pushButton.setGeometry(QtCore.QRect(160, 50, 91, 41))
    font = QtGui.QFont()
    font.setFamily("YaHei Consolas Hybrid")
    font.setPointSize(10)
    self.pushButton.setFont(font)
    self.pushButton.setObjectName("pushButton")

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

def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "对话框"))
    self.pushButton.setText(_translate("Form", "弹出对话框"))

class MyMainForm(QMainWindow, Ui_Form):

def __init__(self, parent=None):
    super(MyMainForm, self).__init__(parent)
    self.setupUi(self)
    self.pushButton.clicked.connect(self.showMsg)

def showMsg(self):
    QMessageBox.information(self, '信息提示对话框','前方右拐到达目的地',QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)
    QMessageBox.question(self, "提问对话框", "你要继续搞测试吗?", QMessageBox.Yes | QMessageBox.No)
    QMessageBox.warning(self, "警告对话框", "继续执行会导致系统重启,你确定要继续?", QMessageBox.Yes | QMessageBox.No)
    QMessageBox.critical(self, "严重错误对话框", "数组越界,程序异常退出", QMessageBox.Yes | QMessageBox.No,)
    QMessageBox.about(self, "关于对话框", "你的Windows系统是DOS1.0")

if name == "__main__":

app = QApplication(sys.argv)
myWin = MyMainForm()
myWin.show()
sys.exit(app.exec_())

复制代码
QInputDialog标准对话框控件
QInputDialog控件是一个标准对话框,用于获取用户输入信息,QInputDialog控件可以提供数字、字符串输入或提供下拉列表选择。

针对QInputDialog对话框控件的使用,我们主要考虑2个问题:1、如何在弹出对话框供用户输入,2、如何获取用户输入。

QInputDialog常用方法:

getint():从控件中获得标准整数输入

getDouble():从控件中获得标准浮点数输入

getText():从控件中获得标准字符串的输入

getItem() :从控件中获得列表里的选项输入

说明:QInputDialog控件

完整代码如下:

复制代码

-- coding: utf-8 --

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialog

class Ui_Form(object):

def setupUi(self, Form):
    Form.setObjectName("Form")
    Form.resize(382, 190)
    font = QtGui.QFont()
    font.setPointSize(9)
    font.setBold(False)
    font.setWeight(50)
    Form.setFont(font)
    self.GetIntlineEdit = QtWidgets.QLineEdit(Form)
    self.GetIntlineEdit.setGeometry(QtCore.QRect(150, 30, 150, 31))
    self.GetIntlineEdit.setText("")
    self.GetIntlineEdit.setObjectName("GetIntlineEdit")
    self.GetstrlineEdit = QtWidgets.QLineEdit(Form)
    self.GetstrlineEdit.setGeometry(QtCore.QRect(150, 80, 150, 31))
    self.GetstrlineEdit.setObjectName("GetstrlineEdit")
    self.GetItemlineEdit = QtWidgets.QLineEdit(Form)
    self.GetItemlineEdit.setGeometry(QtCore.QRect(150, 130, 150, 31))
    self.GetItemlineEdit.setObjectName("GetItemlineEdit")
    self.getIntButton = QtWidgets.QPushButton(Form)
    self.getIntButton.setGeometry(QtCore.QRect(50, 30, 80, 31))
    self.getIntButton.setObjectName("getIntButton")
    self.getStrButton = QtWidgets.QPushButton(Form)
    self.getStrButton.setGeometry(QtCore.QRect(50, 80, 80, 31))
    self.getStrButton.setObjectName("getStrButton")
    self.getItemButton = QtWidgets.QPushButton(Form)
    self.getItemButton.setGeometry(QtCore.QRect(50, 130, 80, 31))
    self.getItemButton.setObjectName("getItemButton")

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

def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "QInputDialog例子"))
    self.getIntButton.setText(_translate("Form", "获取整数"))
    self.getStrButton.setText(_translate("Form", "获取字符串"))
    self.getItemButton.setText(_translate("Form", "获取列表选项"))

class MyMainForm(QMainWindow, Ui_Form):

def __init__(self, parent=None):
    super(MyMainForm, self).__init__(parent)
    self.setupUi(self)
    self.getIntButton.clicked.connect(self.getInt)
    self.getStrButton.clicked.connect(self.getStr)
    self.getItemButton.clicked.connect(self.getItem)

def getInt(self):
    num, ok = QInputDialog.getInt(self, 'Integer input dialog', '输入数字')
    if ok and num:
       self.GetIntlineEdit.setText(str(num))

def getStr(self):
    text, ok=QInputDialog.getText(self, 'Text Input Dialog', '输入姓名:')
    if ok and text:
        self.GetstrlineEdit.setText(str(text))

def getItem(self):
    items=('C', 'C++', 'C#', 'JAva', 'Python')
    item, ok=QInputDialog.getItem(self, "select input dialog", '语言列表', items, 0, False)
    if ok and item:
        self.GetItemlineEdit.setText(str(item))

if name == "__main__":

app = QApplication(sys.argv)
myWin = MyMainForm()
myWin.show()
sys.exit(app.exec_())

复制代码
关键代码介绍:

QInputDialog.getInt(self, 'Integer input dialog', '输入数字') -> 输入整数对话框

QInputDialog.getText(self, 'Text Input Dialog', '输入姓名:') -> 输入字符串对话框

QInputDialog.getItem(self, "select input dialog", '语言列表', items, 0, False) -> 下拉列表选择对话框

QFileDialog文件对话框
QFileDialog是用于打开和保存文件的标准对话框。使用QFileDialog控件主要考虑2个场景:使用该控件提供用户选择目录或文件,并保存选择目录或文件的路径。简单说就是实现类似word/Notepad++文件打开功能。如下

针对上述场景,QFileDialog控件实现的主要方法:

QFileDialog.getOpenFileName():获取单个文件路径

QFileDialog.getOpenFileNames():获取多个文件路径

QFileDialog.getExistingDirectory():获取文件夹路径

完整代码如下:

复制代码

-- coding: utf-8 --

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialog,QFileDialog

class Ui_Form(object):

def setupUi(self, Form):
    Form.setObjectName("Form")
    Form.resize(443, 120)
    self.widget = QtWidgets.QWidget(Form)
    self.widget.setGeometry(QtCore.QRect(50, 40, 301, 25))
    self.widget.setObjectName("widget")
    self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
    self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
    self.horizontalLayout.setObjectName("horizontalLayout")
    self.openFileButton = QtWidgets.QPushButton(self.widget)
    self.openFileButton.setObjectName("openFileButton")
    self.horizontalLayout.addWidget(self.openFileButton)
    self.filePathlineEdit = QtWidgets.QLineEdit(self.widget)
    self.filePathlineEdit.setObjectName("filePathlineEdit")
    self.horizontalLayout.addWidget(self.filePathlineEdit)

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

def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "QFileDialog打开文件例子"))
    self.openFileButton.setText(_translate("Form", "打开文件"))

class MyMainForm(QMainWindow, Ui_Form):

def __init__(self, parent=None):
    super(MyMainForm, self).__init__(parent)
    self.setupUi(self)
    self.openFileButton.clicked.connect(self.openFile)

def openFile(self):
    get_directory_path = QFileDialog.getExistingDirectory(self,
                                "选取指定文件夹",
                                "C:/")
    self.filePathlineEdit.setText(str(get_directory_path))

    get_filename_path, ok = QFileDialog.getOpenFileName(self,
                                "选取单个文件",
                               "C:/",
                                "All Files (*);;Text Files (*.txt)")
    if ok:
        self.filePathlineEdit.setText(str(get_filename_path))

    get_filenames_path, ok = QFileDialog.getOpenFileNames(self,
                                "选取多个文件",
                               "C:/",
                                "All Files (*);;Text Files (*.txt)")
    if ok:
        self.filePathlineEdit.setText(str(' '.join(get_filenames_path)))

if name == "__main__":

app = QApplication(sys.argv)
myWin = MyMainForm()
myWin.show()
sys.exit(app.exec_())

复制代码
关键代码介绍

QFileDialog.getOpenFileName(self,"选取单个文件","C:/","All Files (*);;Text Files (*.txt)") -> 获取单个指定文件的绝对路径

getOpenFileName()参数说明:

第1个参数:用于指定父组件

第2个参数:对话框标题

第3个参数:对话框显示时默认打开的目录。"."表示当前程序所在目录,“/”表示当前盘下的根目录。

第4个参数:对话框中文件扩展名过滤器。All Files (*);;Text Files (*.txt)表示可以选择所有文件类型或者只显示.txt后缀的文件类型。

QFileDialog.getExistingDirectory(self,"选取指定文件夹","C:/") -> 获取指定文件夹的绝对路径

QFileDialog.getOpenFileNames(self,"选取多个文件","C:/","All Files ();;Text Files (.txt)") -> 获取多个指定文件的绝对路径

小结
本文介绍了消息弹出对话框、用户输入对话框以及文件打开对话框的基本使用方法。内容覆盖了这三类控件的基本使用场景。可以开始动手尝试了。。
原文地址https://www.cnblogs.com/linyfeng/p/11223711.html

相关文章
|
17天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
26天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
21 1
|
1月前
|
存储 并行计算 Java
Python读取.nc文件的方法与技术详解
本文介绍了Python中读取.nc(NetCDF)文件的两种方法:使用netCDF4和xarray库。netCDF4库通过`Dataset`函数打开文件,`variables`属性获取变量,再通过字典键读取数据。xarray库利用`open_dataset`打开文件,直接通过变量名访问数据。文中还涉及性能优化,如分块读取、使用Dask进行并行计算以及仅加载所需变量。注意文件路径、变量命名和数据类型,读取后记得关闭文件(netCDF4需显式关闭)。随着科学数据的增长,掌握高效处理.nc文件的技能至关重要。
110 0
|
1月前
|
Python
python中文件和异常处理方法(二)
python中文件和异常处理方法(二)
13 0
|
1月前
|
Python
python中文件和异常处理方法(一)
python中文件和异常处理方法(一)
29 0
|
1月前
|
Python
python中文件和异常处理方法(三)
python中文件和异常处理方法(三)
19 0
|
1天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
1天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
23 0
|
1天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
9 0
|
1天前
|
数据安全/隐私保护 Python
Python文件与目录操作:面试中的高频考点
【4月更文挑战第15天】本文介绍了Python文件和目录操作的面试重点,包括文件的读写、目录遍历及权限管理。强调了文件关闭、异常处理、特殊文件判断以及权限位和权限字符串的理解。提供了代码示例,如读写文件、遍历目录和更改文件权限,帮助读者在面试中表现出色。掌握这些技能将对编程求职之路大有裨益。
15 0