如何防止主窗口关闭

时间:2019-08-23 15:21:08

标签: python exception pyqt5

我编写了一个代码,该代码打开带有textarea的窗口。我们可以清除该文本区域,保存该文本区域或打开其他文本区域。

我面临的问题是,当我尝试关闭或保存文本区域而不对对话框进行任何操作时,主窗口正在关闭。我不希望它关闭。我该怎么解决?

关闭保存窗口时,出现此错误:

  

流程结束,退出代码为1073741845

import os
import sys
from PyQt5.QtWidgets import QPushButton,QApplication,QVBoxLayout,QWidget,QLabel,QTextEdit,QHBoxLayout,QFileDialog


class NotePad(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.textname = QTextEdit()

        self.clear = QPushButton("Clear")
        self.open = QPushButton("Open")
        self.save = QPushButton("Save")

        h_box = QHBoxLayout()

        h_box.addWidget(self.clear)
        h_box.addWidget(self.open)
        h_box.addWidget(self.save)

        v_box = QVBoxLayout()

        v_box.addWidget(self.textname)

        v_box.addLayout(h_box)

        self.setLayout(v_box)

        self.clear.clicked.connect(self.clean)
        self.open.clicked.connect(self.isopen)
        self.save.clicked.connect(self.saved)
        self.show()


    def clean(self):
        self.textname.clear()

    def isopen(self):
        file_name = QFileDialog.getOpenFileName(self,"Open",os.getenv("HOME"))

        with open(file_name[0],"r",encoding="utf-8") as file:
            self.textname.setText(file.read())

    def saved(self):

        file_name = QFileDialog.getSaveFileName(self,"Save",os.getenv("HOME"))

        with open(file_name[0],"w",encoding="utf-8") as file:
            file.write(self.textname.toPlainText())



app = QApplication(sys.argv)

pencere = NotePad()

sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

在关闭“文件打开”或“文件保存”弹出窗口时,如果没有任何有效的操作,则会在各个函数中获得异常。

因此,您应该尝试优雅地处理这些异常。关于如何处理它们完全取决于您,但是要捕获异常,您必须在Python中使用'try','except','finally'关键字。像这样:

def isopen(self):
    file_name = QFileDialog.getOpenFileName(self,"Open",os.getenv("HOME"))
    try:
        with open(file_name[0],"r",encoding="utf-8") as file:
            self.textname.setText(file.read())
    except:
        pass  # Add code for what you want to do here


def saved(self):
    file_name = QFileDialog.getSaveFileName(self,"Save",os.getenv("HOME"))
    try:
        with open(file_name[0],"w",encoding="utf-8") as file:
            file.write(self.textname.toPlainText())
    except:
        pass  # Add code for what you want to do here