Python 尝试在PyQT5中打开文件时出现无效文件错误
我正在尝试制作一个基本的文本编辑器,我正在使用PYQT5进行编辑,但是当我尝试打开或保存一个文件时,会出现错误,对于open,我会:Python 尝试在PyQT5中打开文件时出现无效文件错误,python,python-3.x,pyqt,qt5,pyqt5,Python,Python 3.x,Pyqt,Qt5,Pyqt5,我正在尝试制作一个基本的文本编辑器,我正在使用PYQT5进行编辑,但是当我尝试打开或保存一个文件时,会出现错误,对于open,我会: 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/GitH
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 (*.*)')
通过save,我得到:
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())
非常感谢您的帮助。
self.filename
是一个元组,因此您显然不能将其视为字符串,该方法返回了两个元素,您希望第一个元素如此解包:
self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")
或索引:
self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', ".", "Files (*.*)")[0]
通过这里找到它:tools/+bug/1729066