取消保存时,PyQt getsavefilename显示错误“Python已停止工作”

时间:2018-01-26 12:33:06

标签: python pyqt pyqt5 qfiledialog

从textedit保存文件时, getsavefilename出现问题。

当我保存文件时它正在运行没有问题,但是当我想关闭保存对话框而不保存它时会给我一个错误:

  

python已停止工作

我正在使用python 3.6

代码

def fileSave(self):
    filename = QFileDialog.getSaveFileName(self, 'Save A File', '/home')

    with open(filename[0], 'w') as f:
        text = self.textEdit.toPlainText()
        f.write(text)
        f.close()

错误截图   1

1 个答案:

答案 0 :(得分:1)

当您取消QFileDialog时,它将作为空文本返回,并且当您要打开具有不存在名称的文件时,它会生成该错误。此外,如果您使用with打开文件,则无需关闭文件,只需退出with它将自动关闭

def fileSave(self):
    filename, _ = QFileDialog.getSaveFileName(self, 'Save A File', '/home')

    if filename != "":
        with open(filename, 'w') as f:
            text = self.textEdit.toPlainText()
            f.write(text)

<强>更新

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtPrintSupport import *

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QVBoxLayout(self)
        self.textEdit = QTextEdit()
        self.button = QPushButton("Print")
        lay.addWidget(self.textEdit)
        lay.addWidget(self.button)

        self.button.clicked.connect(self.filePrintPdf)

    def filePrintPdf(self): 
        fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None, "PDF files (.pdf);;All Files ()") 
        if fn != "": 
            if QFileInfo(fn).suffix() == "": fn += '.pdf' 
        printer = QPrinter(QPrinter.HighResolution) 
        printer.setOutputFormat(QPrinter.PdfFormat) 
        printer.setOutputFileName(fn) 
        self.textEdit.document().print_(printer)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())