简体   繁体   中英

How to Python tkinter image insert relative path method

There's something I want to make, so I'm learning tkinter.

The relative route is not recognized.

Example code. Suppose that hyunju.png is in the corresponding.py folder.

import tkinter

root = tkinter.Tk()
root.title("tk")
canvas = tkinter.Canvas(root, width=400, height=600)
canvas.pack()
gazou = tkinter.PhotoImage(file="hyunju.png")
canvas.create_image(200, 300, image=gazou)
root.mainloop()

tkinter.TclError: couldn't open "hyunju.png": no such file or directory

I'm having a hard time because if I use Copy path, there will be a problem when I share or change files.

The editor used is VS code and OS is window 10.

help for me thank you

Depending on hardcoded relative paths should be avoided in this scenario, as they're often times unreliable . Depending on your IDE and even OS it may work or not.

Thus, You should choose a more dynamic better an approach like the following:

import pathlib, os
img_file_name = "hyunju.png"
current_dir = pathlib.Path(__file__).parent.resolve() # current directory
img_path = os.path.join(current_dir, img_file_name) # join with your image's file name

As long as the image file is guaranteed to be in the same directory as the script being executed, it does not matter what IDE / OS you're on - it will work.

I had the same problem and I don't know if it might be the same case for you, just check that you are opening the whole project and not just the.py file if you are working on an IDE like, for example, Visual Studio Code, because else it won't be able to find any relatives paths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM