python-3.x - 当我尝试在 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岁,所以请不要有毒
解决方案
这是 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
,我们想要的是文件的父文件夹。
推荐阅读
- unity3d - 我已经实现了水平滑动以将玩家旋转 90 度,但是旋转相机会破坏我的滑动逻辑。我该如何解决这个问题?
- python - (python 初学者)有没有其他方法可以根据用户输入将 str() 转换为 int() 和 float() ?
- python - 如何根据先前索引处新创建的值执行计算?
- eclipse-hono - 无法在 Hono 中使用基于 X.509 的身份验证注册租户
- scala - 为在 Scala 中并行运行 Databricks 笔记本的未来序列添加重试
- dictionary - 颤振\:未处理的异常:迭代期间的并发修改:_LinkedHashMap len:0
- html - 使用 flexbox 连续调整 3 个框
- javascript - 从一个类型类数组Angular 7的数组中访问数据
- oracle - 根据 Oracle 中的百分比计算更新多个列
- c++ - 如何从二进制文件中读取字符串?