PyQt学习之单个和多个文件选择并显示文件名

1. 采用Qt_Designer画出页面 ,保存名为test.ui,并生成test.py

流程可参考:PyQT学习之Stacked Widget控件

PyQt学习之单个和多个文件选择并显示文件名_第1张图片

生成的test.py代码:

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

# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(679, 446)
        self.pushButton_1 = QtWidgets.QPushButton(Form)
        self.pushButton_1.setGeometry(QtCore.QRect(50, 30, 201, 28))
        self.pushButton_1.setObjectName("pushButton_1")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(420, 30, 201, 28))
        self.pushButton_2.setObjectName("pushButton_2")
        self.textBrowser = QtWidgets.QTextBrowser(Form)
        self.textBrowser.setGeometry(QtCore.QRect(50, 70, 571, 351))
        self.textBrowser.setObjectName("textBrowser")

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton_1.setText(_translate("Form", "打开单个文件"))
        self.pushButton_2.setText(_translate("Form", "打开多个文件"))

2. 编写main.py

# encoding=utf-8
import sys
from PyQt5.QtWidgets import *

import test


class fileSelect(QWidget, test.Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton_1.clicked.connect(self.btn_single)
        self.pushButton_2.clicked.connect(self.btn_multi)

    def btn_single(self):
        # 选择单个文件
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  "选取文件",
                                                  r"D:\Project",
                                                  "All Files (*);;Text Files (*.csv)")
        self.textBrowser.setText(filename)
    def btn_multi(self):
        # 选择多个文件
        files, filetype = QFileDialog.getOpenFileNames(self,
                                                       "多文件选择",
                                                       r"D:\Project",  # 起始路径
                                                       "All Files (*);;Text Files (*.csv)")
        # 清屏
        self.textBrowser.clear()
        # 将选择的文件名都打印到textBrowser控件中
        for file in files:
            self.textBrowser.append(file)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = fileSelect()
    w.show()
    sys.exit(app.exec_())

3. 单个文件测试:

PyQt学习之单个和多个文件选择并显示文件名_第2张图片


4. 多个文件测试:

PyQt学习之单个和多个文件选择并显示文件名_第3张图片

 

 

你可能感兴趣的:(pyqt,python)