There is a simple text editor. Faced a problem: when I clicked on the "X" button (red cross), in the file selection dialog box, I get the crash:

"Python program is not working"

Code:

#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QFileDialog, QApplication, QWidget, QMessageBox from PyQt5.QtGui import QIcon class Notepad(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.setWindowIcon(QIcon("..\\source\\python.png")) self.statusBar() openFile = QAction(QIcon('..\\source\\open.png'), 'Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open new File') openFile.triggered.connect(self.showDialog) saveFile = QAction(QIcon('..\\source\\save.png'), 'Save', self) saveFile.setShortcut('Ctrl+S') saveFile.setStatusTip('Save new File') saveFile.triggered.connect(self.saveDialog) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(openFile) fileMenu.addAction(saveFile) self.setGeometry(300, 200, 750, 400) self.setWindowTitle('Notepad') self.show() def showDialog(self): fname = QFileDialog.getOpenFileName(self, 'Open file')[0] f = open(fname, 'r') with f: text = f.read() self.textEdit.setText(text) def saveDialog(self): fname = QFileDialog.getSaveFileName(self, 'Save file')[0] file = open(fname, 'w') text = self.textEdit.toPlainText() file.write(text) file.close() if __name__ == '__main__': app = QApplication(sys.argv) ex = Notepad() sys.exit(app.exec_()) 

The thought came that the reason is the inheritance from the QMainWindow class, but I did not think up how to solve the issue. Please help!

  • Could you replace the picture with a plain text. The picture will once be deleted and your link will become a bat. - 0xdb

1 answer 1

getOpenFileName - returns a tuple where the first element is the path to the selected file, since in your case the file is not selected - the line is empty. Before further actions, you need to check the length of the string with the path to the file:

 def showDialog(self): fname = QFileDialog.getOpenFileName(self, 'Open file')[0] if len(fname): f = open(fname, 'r') with f: text = f.read() self.textEdit.setText(text) 
  • alternatively: filename, _ = QFileDialog.getOpenFileName(self, 'Open file') . Also, instead of if len(seq) in Python, it’s customary to write if seq . That is, if filename: .. says "if the file name was given, then .." Aside: I understand that you copied the code from the question code, but the meaning of the file outside of the with construction is not visible. Instead, with open(filename) as file:\n set.textEdit.setText(file.read()) or set.textEdit.setText(Path(filename).read_text()) - jfs