user14670421
user14670421

Reputation:

VSCode raising error when I try to import an Image in Python

I am using Visual Studio Code Community Edition.

I am using code like below and running it:

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

And when I try to run this, I get this error:

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

I have quadruple-checked that this exists. I have the script being run in the directory where Resources is and this is happening. Here's the filetree:

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

Is this some sort of VSCode bug or is it something with the directories?

I'm only 11, so please don't be toxic

Upvotes: 0

Views: 1531

Answers (1)

Hyperx837
Hyperx837

Reputation: 833

This is the normal behavior of the VS Code python extension. It automatically cd into workspace root. So you have to define the path from the workspace root to the file. while this method works on VS Code, this code will break on other editors because they don't cwd into the workspace folder. And also if you open the script from VS Code but this time with an in a different workspace (maybe previous workspace folder's parent or something) it would throw an error. So the solution to this would be something like this:

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 your code didn't run on terminal, if statement will return False thus the indented block wouldn't work. However, usually when code isn't running on terminal cwd is the parent folder of the file as we want.

Upvotes: 1

Related Questions