【发布时间】:2023-02-14 02:29:34
【问题描述】:
我正在开发一个项目,其中有一个功能可以显示打开的文件对话框并打印出所选文件的路径。
我的代码如下所示:
def openFile(self):
filePath = tkinter.filedialog.askopenfile(initialdir=startingDir, title="Open File", filetypes=(("Open a .txt file", "*.txt"), ("All files", "*.*")))
if filePath == '':
tkinter.messagebox.showwarning("Warning", "You didn't select a file.")
else:
print(filePath)
但是,我收到来自 Visual Studio Code 的错误:
Argument of type "IO[Incomplete] | None" cannot be assigned to parameter "file" of type "_OpenFile" in function "open"
这个来自IDLE:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\benri\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\benri\AppData\Local\Programs\Python\Python310\lib\site-packages\customtkinter\widgets\ctk_button.py", line 377, in clicked
self.command()
File "C:\Users\benri\OneDrive\Desktop\My Files\Apps and Programs\Windows Programs\Python\TexType\editFile.py", line 51, in openFile
mainFile = open(filePath, "r")
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
问题是什么,我该如何解决?
我刚刚发现,如果我使用语法 mainFile = open(str(filePath), "r"),Python 会给我以下错误:
FileNotFoundError:[Errno 2] 没有这样的文件或目录:'PY_VAR0'
建议这种使用
str()的方法会导致变量内容无效。
【问题讨论】:
-
发布的代码中不存在导致异常的行。最好提供一个minimal reproducible example。
标签: python-3.x tkinter exception