224.md 1.5 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
# QT4 文件对话框

> 原文: [https://pythonspot.com/qt4-file-dialog/](https://pythonspot.com/qt4-file-dialog/)

在这个简短的教程中,您将学习如何创建文件对话框并加载其文件内容。 使用文件访问的许多应用程序都需要文件对话框。

**相关课程:**

*   [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)

**文件对话框示例** 要在 [PyQT](https://pythonspot.com/pyqt4/) 中获取文件名(而非文件数据),可以使用以下行:

```
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')

```

如果您使用的是 Microsoft Windows,请使用

```
filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')

```

下面的示例(包括加载文件数据):

```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from 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 title
w.setWindowTitle("Hello World!")

# Get filename using QFileDialog
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
print(filename)

# print file contents
with open(filename, 'r') as f:
    print(f.read())

# Show window
w.show()

sys.exit(a.exec_())

```

结果(输出可能因您的操作系统而异):

![pyqt_file_open](img/a6f06b37951c44452f79efd047298429.jpg) PyQt File Open Dialog.

[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)