侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法

Python  /  管理员 发布于 5年前   511

本文主要介绍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 sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBoxclass 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 sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialogclass 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 sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialog,QFileDialogclass 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)") -> 获取多个指定文件的绝对路径

小结

  本文介绍了消息弹出对话框、用户输入对话框以及文件打开对话框的基本使用方法。内容覆盖了这三类控件的基本使用场景。可以开始动手尝试了。。

以上所述是小编给大家介绍的PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!


  • 上一条:
    pytorch中如何使用DataLoader对数据集进行批处理的方法
    下一条:
    PyQt5通信机制 信号与槽详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客