原文: https://pythonspot.com/pyqt5-file-dialog/

PyQt5 支持(本机)文件对话框:打开文件,打开文件和保存文件。 通过调用 PyQt5 中包含的功能,您将获得默认的文件对话框,而无需从头开始重新创建这些对话框。

需要导入QFileDialog

文件对话框示例

使用的方法是QFileDialog.getOpenFileName()QFileDialog.getOpenFileNames()QFileDialog.getSaveFileName()。 使用方法参数可以指定默认目录,文件类型和默认文件名。

PyQt5 文件对话框 - 图1

下面的代码将显示所有文件对话框:

  1. import sys
  2. from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
  3. from PyQt5.QtGui import QIcon
  4. class App(QWidget):
  5. def __init__(self):
  6. super().__init__()
  7. self.title = 'PyQt5 file dialogs - pythonspot.com'
  8. self.left = 10
  9. self.top = 10
  10. self.width = 640
  11. self.height = 480
  12. self.initUI()
  13. def initUI(self):
  14. self.setWindowTitle(self.title)
  15. self.setGeometry(self.left, self.top, self.width, self.height)
  16. self.openFileNameDialog()
  17. self.openFileNamesDialog()
  18. self.saveFileDialog()
  19. self.show()
  20. def openFileNameDialog(self):
  21. options = QFileDialog.Options()
  22. options |= QFileDialog.DontUseNativeDialog
  23. fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
  24. if fileName:
  25. print(fileName)
  26. def openFileNamesDialog(self):
  27. options = QFileDialog.Options()
  28. options |= QFileDialog.DontUseNativeDialog
  29. files, _ = QFileDialog.getOpenFileNames(self,"QFileDialog.getOpenFileNames()", "","All Files (*);;Python Files (*.py)", options=options)
  30. if files:
  31. print(files)
  32. def saveFileDialog(self):
  33. options = QFileDialog.Options()
  34. options |= QFileDialog.DontUseNativeDialog
  35. fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options)
  36. if fileName:
  37. print(fileName)
  38. if __name__ == '__main__':
  39. app = QApplication(sys.argv)
  40. ex = App()
  41. sys.exit(app.exec_())

下载 PyQT5 示例