PyQt5--QFileDiaglog

时间:2025-01-05 14:03:08
 # -*- coding:utf-8 -*-
'''
Created on Sep 17, 2018 @author: SaShuangYiBing Comment:
'''
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication,QMainWindow,QFileDialog,QTextEdit,QAction class New_test(QMainWindow):
def __init__(self):
super().__init__()
self.initUI() def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar() openFile = QAction(QIcon('exit.png'),'Open',self)
openFile.setShortcut('Crtl+O')
openFile.setStatusTip('Open new file')
openFile.triggered.connect(self.showdiaglog) menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile) self.setGeometry(300,300,350,300)
self.setWindowTitle('File Diaglog')
self.show() def showdiaglog(self):
try:
fname = QFileDialog.getOpenFileName(self,'Open file','/home') if fname[0]:
with open(fname[0],'r',encoding='utf-8') as f: # 在Python3中使用open时后面需要带上编码方式,否则易引起打开非utf-8编码字符时会报错
data = f.read()
self.textEdit.setText(data)
except Exception as e:
print (e) if __name__ == '__main__':
app = QApplication(sys.argv)
ex = New_test()
sys.exit(app.exec_())

PyQt5--QFileDiaglog