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

所属分类: 脚本专栏 / python 阅读数: 1070
收藏 0 赞 0 分享

本文主要介绍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)") -> 获取多个指定文件的绝对路径

小结

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

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

更多精彩内容其他人还在看

Python中模块string.py详解

这篇文章主要介绍了Python中模块之string.py的相关资料,文中介绍的非常详细,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

Python中关键字nonlocal和global的声明与解析

这篇文章主要给大家介绍了关于Python中关键字nonlocal和global的声明与解析的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

python中pandas.DataFrame对行与列求和及添加新行与列示例

pandas是python环境下最有名的数据统计包,而DataFrame翻译为数据框,是一种数据组织方式,这篇文章主要给大家介绍了python中pandas.DataFrame对行与列求和及添加新行与列的方法,文中给出了详细的示例代码,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

Python中str.format()详解

本文主要给大家详细介绍的是python编程中str.format()的基本语法和高级用法,非常的详细,并附有示例,希望大家能够喜欢
收藏 0 赞 0 分享

python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)

这篇文章主要介绍了python中pandas.DataFrame的简单操作方法,其中包括创建、索引、增添与删除等的相关资料,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

Python IDLE 错误:IDLE''s subprocess didn''t make connection 的解决方案

这篇文章主要介绍了Python IDLE 错误:IDLE's subprocess didn't make connection 的解决方案的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Python中类型检查的详细介绍

Python是一种非常动态的语言,函数定义中完全没有类型约束。下面这篇文章主要给大家详细介绍了Python中类型检查的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

利用python程序生成word和PDF文档的方法

这篇文章主要给大家介绍了利用python程序生成word和PDF文档的方法,文中给出了详细的介绍和示例代码,相信对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

python用装饰器自动注册Tornado路由详解

这篇文章主要给大家介绍了python用装饰器自动注册Tornado路由,文中给出了三个版本的解决方法,有需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

让python 3支持mysqldb的解决方法

这篇文章主要介绍了关于让python 3支持mysqldb的解决方法,文中给出解决的示例代码,相信对大家具有一定的参考价值,有需要的朋友可以一起来看看。
收藏 0 赞 0 分享
查看更多