[英]PyQt getsavefilename shows error “Python has stopped working” when canceling save
I have a problem with pyqt5 getsavefilename
when saving a file from a textedit. 从textedit保存文件时, pyqt5 getsavefilename
出现问题。
When I am saving a file it is working there is no problem but when I want to close the save dialog without saving it is giving me error: 当我保存文件时,它没有问题,但是当我不保存就关闭保存对话框时,出现错误:
python has stopped working python已经停止工作
I'am using python 3.6 我正在使用python 3.6
Code 码
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()
Error screenshot 错误截图
When you cancel the QFileDialog
it returns as an empty text, and when you want to open a file with a non-existent name, it generates that error. 当您取消QFileDialog
它以空文本形式返回,并且当您要打开一个不存在的名称的文件时,它将生成该错误。 Also if you are using with
to open the file it is not necessary to close the file, just quit the with
it will be closed automatically 另外,如果您使用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)
Update: 更新:
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_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.