从textedit保存文件时,pyqt5 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()
错误截图
答案 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_())