【问题标题】:Tkinter: Get file path from Tkinter filedialogTkinter:从 Tkinter filedialog 获取文件路径
【发布时间】: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() 的方法会导致变量内容无效。

【问题讨论】:

标签: python-3.x tkinter exception


【解决方案1】:

askopenfile返回一个文件处理, 不是文件姓名.您选择的任何文件都会自动打开并返回句柄。

您不能将文件句柄传递给 open。如果你想要文件姓名,请使用 askopenfilename 而不是 askopenfile。或者,只使用 askopenfile 返回的已经打开的文件。

【讨论】:

  • 我认为那行不通!在收到“FileNotFoundError: [Errno 2] No such file or directory: 'PY_VAR0'”错误后,我调查了变量的内容,发现它包含值“PY_VARO”。不知道这意味着什么,是吗?谢谢!
  • @BentheCoder:这是 Tkinter 变量的内部名称。
  • @Brian Oakley:但是你如何获得变量的字符串?
猜你喜欢
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多