首页 > 解决方案 > 当我尝试在 Python 中导入图像时 VSCode 引发错误

问题描述

我正在使用 Visual Studio Code 社区版。

我正在使用如下代码并运行它:

from tkinter import *
tk = Tk()
img = PhotoImage(pathtoimage)
Button(tk, image=img).pack()
tk.mainloop()

当我尝试运行它时,我收到了这个错误:

_tkinter.TclError: couldn't open "Resources/ytbanner.png": no such file or directory

我已经四次检查这是否存在。我在 Resources 所在的目录中运行脚本,并且正在发生这种情况。这是文件树:

Path to my desktop
    Projectname
        Script I'm using
        Resources
            PNG image I want to use

这是某种 VSCode 错误还是与目录有关?

我才11岁,所以请不要有毒

标签: python-3.ximagetkintervisual-studio-codepng

解决方案


这是 VS Code python 扩展的正常行为。它自动cd进入工作区根目录。所以你必须定义从工作空间根到文件的路径。虽然此方法适用于 VS Code,但此代码会在其他编辑器上中断,因为它们不会cwd进入工作区文件夹。而且,如果您从 VS Code 打开脚本,但这次在不同的工作区(可能是以前的工作区文件夹的父级或其他东西)中打开脚本,则会引发错误。所以这个问题的解决方案是这样的:

import os
import sys

if sys.argv:
    filepath = sys.argv[0]
    folder, filename = os.path.split(filepath)
    os.chdir(folder) # now your working dir is the parent folder of the script

# and your code

如果您的代码没有在终端上运行,则 if 语句将返回,False因此缩进的块将不起作用。但是,通常当代码没有在终端上运行时cwd,我们想要的是文件的父文件夹。


推荐阅读