通过QFileDialog从QPlainTextEdit保存文本并创建.txt文件 [英] Saving text from QPlainTextEdit by QFileDialog and creating .txt file

查看:1006
本文介绍了通过QFileDialog从QPlainTextEdit保存文本并创建.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在保存笔记(QPlainTextEdit中的文本)方面遇到麻烦.我只需要保存为txt格式.键入文本并单击按钮后,程序将显示错误预期的字符串或类似字节的对象而不是nonetype".记事本的程序从类fileeki开始,直到类fileush.我使用Python 3.7,PyQt5和QtDesigner来创建界面.打开效果很好,但不能保存.请下载项目的所有元素.还有一些模块,必须安装.谢谢尝试.

I have troubles with saving note(text from QPlainTextEdit). I need only saving in txt format. After typing text and clicking button program displays error 'expected string or bytes-like object not nonetype'.Notepad's program starts from class fileeki till class fileush. I use Python 3.7, PyQt5 and QtDesigner for creating interface.Opening works well, but not saving.Please download all elements of my project. Also there is modules, which you must install.Thanks for trying.

import sys

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPlainTextEdit
from PyQt5.QtWidgets import QLabel, QPushButton, QMessageBox, QFileDialog
from PyQt5.QtGui import QPixmap


class fileeki(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__()
        uic.loadUi('uineweki.ui', self)

        self.path = None

        self.pushButton.clicked.connect(self.opening_run)
        self.pushButton_2.clicked.connect(self.saving_run)
        self.pushButton_3.clicked.connect(self.saveac)
        self.pushButton_5.clicked.connect(self.new_run)

    def dialog_critical(self, s):
        dlg = QMessageBox(self)
        dlg.setText(s)
        dlg.setIcon(QMessageBox.Critical)
        dlg.show()

    def opening_run(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text files (*.txt)")

        if path:
            try:
                with open(path, 'rU') as f:
                    text = f.read()

            except Exception as e:
                self.dialog_critical(str(e))

            else:
                self.path = path
                self.plainTextEdit.setPlainText(text)

    def saving_run(self):
        if self.path is None:

            return self.saveac()

        self._save_to_path(self.path)

    def saveac(self):
        path = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")

        if not path:

            return

        self._save_to_path(self.path)

    def _save_to_path(self, path):
        text = self.plainTextEdit.toPlainText()
        try:
            with open(path, 'w') as f:
                f.write(text)

        except Exception as e:
            self.dialog_critical(str(e))

        else:
            self.path = path

    def new_run(self):
        self.plainTextEdit.clear()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = fileeki()
    ex.show()
    sys.exit(app.exec())

链接到我在github上的项目: https://github.com/iMAGA07/notepadd

Link to my project on github: https://github.com/iMAGA07/notepadd

推荐答案

该错误是因为您实际上并未使用文件对话框中返回的数据:

The error is because you are not actually using the returned data from the file dialog:

    def saveac(self):
        path = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")

        if not path:

            return

        self._save_to_path(self.path) # <-- here!

此外,getSaveFileName静态返回一个元组,该元组由文件路径选定的过滤器字符串组成,如果取消对话框,则它们都可以为空,因此总是会失败.

Also, the getSaveFileName static returns a tuple composed of file path and selected filter strings, and both of them could be empty if the dialog is cancelled, so if not path would always fail.

检查返回的数据并相应地调用_save_to_path:

Check the returned data and call the _save_to_path accordingly:

    def saveac(self):
        path, filter = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")

        if not path:

            return

        self._save_to_path(path)

这篇关于通过QFileDialog从QPlainTextEdit保存文本并创建.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆