在这个简短的教程中,您将学习如何创建文件对话框并加载其文件内容。 使用文件访问的许多应用程序都需要文件对话框。
文件对话框示例
要在 PyQT 中获取文件名(而非文件数据),可以使用以下行:
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
如果您使用的是 Microsoft Windows,请使用
filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')
下面的示例(包括加载文件数据):
#! /usr/bin/env python# -*- coding: utf-8 -*-#import sysfrom PyQt4.QtGui import *# Create an PyQT4 application object.a = QApplication(sys.argv)# The QWidget widget is the base class of all user interface objects in PyQt4.w = QWidget()# Set window size.w.resize(320, 240)# Set window titlew.setWindowTitle("Hello World!")# Get filename using QFileDialogfilename = QFileDialog.getOpenFileName(w, 'Open File', '/')print(filename)# print file contentswith open(filename, 'r') as f:print(f.read())# Show windoww.show()sys.exit(a.exec_())
结果(输出可能因您的操作系统而异):

PyQt 文件打开对话框
