Skip to content Skip to sidebar Skip to footer

Vs Code Does Not Debug Python Correctly

I am trying to make an application with python. But when I try to run it in VS code, it throws an error with VS code as follows: But when I run the code outside VS code, it works

Solution 1:

I think you're right that the problem is related to file directories. It's because all file paths in your code are relative to the current working directory (CWD), so will only be correct when that's the root folder. Apparently this is not the case when you run the code from the VS Code IDE. To fix things you need to make it work regardless of what the CWD is, and to do that you will need to determine their absolute paths at runtime.

I don't really know what your folder structure is, so have assumed it's something like the following:

CPS
│   CPStest.py
│   history.txt
│
└───resources
    ├───animals
    │       panda.png
    │       sloth.png
    │       turtle.png
    │       ...
    │
    └───icon
            CPS.ico

If this is correct, then you can determine the absolute file paths at runtime by extracting the root folder's path from the built-in __file__ variable which contains the path to currently executing script. Once you have the path to this root folder, it's relatively easy to determine the paths to the other files.

In the example code below I'm using the pathlib module to do everything because it's object-oriented and makes doing the steps required very intuitive and readable.

import os
from pathlib import Path
from PIL import ImageTk
import tkinter as tk


# Determine paths based on location of this script.
main_folder_path = Path(__file__).resolve().parent
resources_path = main_folder_path / "resources"
icon_path = resources_path / "icon"
animals_path = resources_path / "animals"

if (main_folder_path / "history.txt").exists():
    print("history.txt exists")
    # (main_folder_path / "history.txt").open('r') as f:#     ...

root = tk.Tk()
root.iconbitmap(icon_path / "CPS.ico")
root.geometry("600x600")
root.minsize(600, 600)
root.maxsize(600, 600)
root.title("CPS Tester")

sloth = ImageTk.PhotoImage(file=animals_path / "sloth.png")
panda = ImageTk.PhotoImage(file=animals_path / "panda.png")
turtle = ImageTk.PhotoImage(file=animals_path / "turtle.png")
buffalo = ImageTk.PhotoImage(file=animals_path / "buffalo.png")
rabbit = ImageTk.PhotoImage(file=animals_path / "rabbit.png")
tiger = ImageTk.PhotoImage(file=animals_path / "tiger.png")
cheetah = ImageTk.PhotoImage(file=animals_path / "cheetah.png")
...

Post a Comment for "Vs Code Does Not Debug Python Correctly"