0

I'm trying to make function that sees if an item is in the cart list and places an image from a folder that I have the images stored in but when I run the code it says filenotfound error and when I looked it up in old threads people said that I have to write the actual path

imagenames=[]

path1="C:\\Users\\3a2b\\Desktop\\lib\\images"
imagelist=os.listdir(path1)
for name in os.listdir(path1):
    imagenames.append(os.path.splitext(name)[0])


def show_cart():
    cartwindow = Toplevel()
    for item in cart:
        for i in range(len(imagenames)):
            if item.title == imagenames[i]:
                print("its there")
                img = ImageTk.PhotoImage(open(os.listdir(path1)[i]))
                label = Label(cartwindow,image=img)
                label.grid(row=0,column=2)


    ```
  • 1
    you should be able to use relative path, based on the directory from which you run your script – juuso Dec 17 '21 at 13:52
  • create a new file `path.py` create a class, method to get and change path. Import it here – abhinit21 Dec 17 '21 at 13:52
  • 2
    It's not very clear to me what exactly it is you are trying to figure out but I think that `os.getcwd()` could help you out. This will print the current working directory's path and you can take it from there (move 1 folder above, 1 folder deeper, etc.). – neisor Dec 17 '21 at 13:53
  • @neisor I used `os.chdir()` and I think but I got this error: mode = Image.getmodebase(mode) – abdallah_mahmoud Dec 17 '21 at 14:01

1 Answers1

-1

If your're running your script in C:\\Users\\3a2b\\Desktop you can reference your images directory as a relative path like .\\lib\\images.

If you're in another directory like C:\\Users\\3a2b\\Documents\\Scripts\\script.py you can reference your image path like ..\\..\\Desktop\\lib\\images or similar.

If you want to play around with navigating around your directory in Python you could always try out something like:

currentPath = 'C:\\Users\\3a2b\\Desktop'
currentPath = os.chdir('..\\..')
print(os.getcwd())
-> 'C:\\Users'

Check out the os package for more info. https://docs.python.org/3/library/os.html

Also, be wary of where you installed your Python distribution, I installed on C: drive once and couldn't access data in another drive D: or E: without some extra hassle.

patataskr
  • 325
  • 5
  • 15
  • check out these for that issue https://stackoverflow.com/questions/17005961/displaying-images-with-tkinter. I'm not familiar with that package so I'm not the best suited to answer that error. You might also want to use `os.walk()` to get the list of images or to iterate over the images in a loop. – patataskr Dec 17 '21 at 14:22
  • This is not a good solution since it suggests hard-coding a path in the code. – Bryan Oakley Dec 17 '21 at 16:25
  • Just communicating fundamentals of path management – patataskr Dec 17 '21 at 20:27