当前位置:   article > 正文

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

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

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

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

生成的test.py代码:

  1. # -*- coding: utf-8 -*-
  2. # Form implementation generated from reading ui file 'test.ui'
  3. #
  4. # Created by: PyQt5 UI code generator 5.15.4
  5. #
  6. # WARNING: Any manual changes made to this file will be lost when pyuic5 is
  7. # run again. Do not edit this file unless you know what you are doing.
  8. from PyQt5 import QtCore, QtGui, QtWidgets
  9. class Ui_Form(object):
  10. def setupUi(self, Form):
  11. Form.setObjectName("Form")
  12. Form.resize(679, 446)
  13. self.pushButton_1 = QtWidgets.QPushButton(Form)
  14. self.pushButton_1.setGeometry(QtCore.QRect(50, 30, 201, 28))
  15. self.pushButton_1.setObjectName("pushButton_1")
  16. self.pushButton_2 = QtWidgets.QPushButton(Form)
  17. self.pushButton_2.setGeometry(QtCore.QRect(420, 30, 201, 28))
  18. self.pushButton_2.setObjectName("pushButton_2")
  19. self.textBrowser = QtWidgets.QTextBrowser(Form)
  20. self.textBrowser.setGeometry(QtCore.QRect(50, 70, 571, 351))
  21. self.textBrowser.setObjectName("textBrowser")
  22. self.retranslateUi(Form)
  23. QtCore.QMetaObject.connectSlotsByName(Form)
  24. def retranslateUi(self, Form):
  25. _translate = QtCore.QCoreApplication.translate
  26. Form.setWindowTitle(_translate("Form", "Form"))
  27. self.pushButton_1.setText(_translate("Form", "打开单个文件"))
  28. self.pushButton_2.setText(_translate("Form", "打开多个文件"))

2. 编写main.py

  1. # encoding=utf-8
  2. import sys
  3. from PyQt5.QtWidgets import *
  4. import test
  5. class fileSelect(QWidget, test.Ui_Form):
  6. def __init__(self):
  7. super().__init__()
  8. self.setupUi(self)
  9. self.pushButton_1.clicked.connect(self.btn_single)
  10. self.pushButton_2.clicked.connect(self.btn_multi)
  11. def btn_single(self):
  12. # 选择单个文件
  13. filename, _ = QFileDialog.getOpenFileName(self,
  14. "选取文件",
  15. r"D:\Project",
  16. "All Files (*);;Text Files (*.csv)")
  17. self.textBrowser.setText(filename)
  18. def btn_multi(self):
  19. # 选择多个文件
  20. files, filetype = QFileDialog.getOpenFileNames(self,
  21. "多文件选择",
  22. r"D:\Project", # 起始路径
  23. "All Files (*);;Text Files (*.csv)")
  24. # 清屏
  25. self.textBrowser.clear()
  26. # 将选择的文件名都打印到textBrowser控件中
  27. for file in files:
  28. self.textBrowser.append(file)
  29. if __name__ == '__main__':
  30. app = QApplication(sys.argv)
  31. w = fileSelect()
  32. w.show()
  33. sys.exit(app.exec_())

3. 单个文件测试:


4. 多个文件测试:

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/264527
推荐阅读
相关标签
  

闽ICP备14008679号