How do I make a code that locates the image inside a folder without using the direct location with C:User. So that whenever I send the GUI to someone, they can run it without any errors. Is there any other codes that I can use?
photo = tk.PhotoImage(file="C:/Users/Me/Downloads/xxxx/Pics/xxxx.png")
label = tk.Label(window, image=photo)
label.place(x=0, y=0, relwidth=1, relheight=1)
CodePudding user response:
Use pathlibe instead, if you want to access user home, it will also work in LINUX OR MacOS as its platform independent
import os
from pathlib import Path
downloadsDirectory = os.path.join(Path.home(),'Downloads')
photo = tk.PhotoImage(file=os.path.join(downloadsDirectory,"xxxx","Pics","xxxx.png"))
label = tk.Label(window, image=photo)
label.place(x=0, y=0, relwidth=1, relheight=1)
CodePudding user response:
Reading a bit between the lines, it sounds like:
- You want to distribute your code by sending a directory or archive to people so that they can run it on their machine
- You have resources inside this package that you'd like to reference
You can't really assume anything about where the user will place this directory on their machine, so you need to work with relative paths.
This line:
photo = tk.PhotoImage(file=os.path.join(downloadsDirectory,"xxxx","Pics","xxxx.png"))
seems to suggest your script is placed in folder xxxx
of the user's Downloads
directory, which means the relative path of the resource is Pics/xxxx.png
.
Based on these assumptions, you could do something like:
from pathlib import Path
script_dir = Path(__file__).parent.absolute()
resource_path = script_dir / "Pics" / "xxxx.png"
photo = tk.PhotoImage(file=str(resource_path)) # use resource_path.as_posix() instead if you want forward slashes on all platforms instead of native path format
label = tk.Label(window, image=photo)
label.place(x=0, y=0, relwidth=1, relheight=1)