-
Notifications
You must be signed in to change notification settings - Fork 0
/
QFileDialogDemo.py
57 lines (45 loc) · 1.65 KB
/
QFileDialogDemo.py
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
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
@author:fangpf
@time: 2020/11/03
"""
import sys
from PyQt5.QtCore import QDir
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout, QLabel, QTextEdit, QFileDialog, QApplication
class QFileDialogDemo(QWidget):
def __init__(self):
super(QFileDialogDemo, self).__init__()
self.btn1 = QPushButton('加载图片')
self.btn2 = QPushButton('加载文本文件')
self.v_layout = QVBoxLayout()
self.image_label = QLabel()
self.contents = QTextEdit()
self.initUI()
def initUI(self):
self.btn1.clicked.connect(self.load_image)
self.btn2.clicked.connect(self.load_text)
self.v_layout.addWidget(self.btn1)
self.v_layout.addWidget(self.image_label)
self.v_layout.addWidget(self.btn2)
self.v_layout.addWidget(self.contents)
self.setLayout(self.v_layout)
self.setWindowTitle('文件对话框演示')
def load_image(self):
frame, _ = QFileDialog.getOpenFileName(self, '打开文件', '.', '图像文件(*.jpg *.png)')
self.image_label.setPixmap(QPixmap(frame))
def load_text(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.AnyFile)
dialog.setFilter(QDir.Files)
if dialog.exec_():
filenames = dialog.selectedFiles()
with open(filenames[0], encoding='utf-8', mode='r') as f:
data = f.read()
self.contents.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QFileDialogDemo()
window.show()
sys.exit(app.exec_())