我正在尝试创建一个基本的文本编辑器,我正在使用PYQT5这样做,但是当我尝试打开或保存文件时出现错误,打开我得到:
File "D:\NicKLz\Documents\GitHub\MiscProjects\TextEditor\txtEditor.py", line 81, in open
with open(self.filename, "r") as file:
TypeError: invalid file: ('D:/NicKLz/Documents/GitHub/MiscProjects/TextEditor/Hello.writer', 'Files (*.*)')
有了保存,我得到了:
File "D:\NicKLz\Documents\GitHub\MiscProjects\TextEditor\txtEditor.py", line 89, in save
if not self.filename.endswith(".writer"):
AttributeError: 'tuple' object has no attribute 'endswith'
以下是我对这些功能的看法:
def open(self):
#Get filename and show only .txt files
self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")
if self.filename:
with open(self.filename, "r") as file:
self.text.setText(file.read())
def save(self):
#Only Open this dialog if there is no filename yet
if not self.filename:
self.filename = QtWidgets.QFileDialog.getSaveFileName(self, "Save File")
#Add the appropriate extension if not currently in place
if not self.filename.endswith(".writer"):
self.filename += ".writer"
#Store Contents and format in html format which QT does a nice job of implementing for us already
with open(self.filename,"w") as file:
file.write(self.text.toHtml())
任何帮助都会非常感激。
答案 0 :(得分:0)
self.filename
是一个元组,所以很明显你不能把它当成一个字符串,从方法中返回两个元素,你想要第一个解压缩:
self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")
或索引:
self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")[0]