如何在不使用 C:User 的直接位置的情況下制作在檔案夾中定位影像的代碼。這樣每當我將 GUI 發送給某人時,他們就可以毫無錯誤地運行它。我可以使用其他任何代碼嗎?
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)
uj5u.com熱心網友回復:
改用 pathlibe,如果你想訪問用戶家,它也可以在 LINUX 或 MacOS 中作業,因為它的平臺獨立
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)
uj5u.com熱心網友回復:
在字里行間讀一點,聽起來像:
- 您想通過向人們發送目錄或存檔來分發您的代碼,以便他們可以在他們的機器上運行它
- 您在此包中有要參考的資源
您無法真正假設用戶將在其機器上放置此目錄的位置,因此您需要使用相對路徑。
這一行:
photo = tk.PhotoImage(file=os.path.join(downloadsDirectory,"xxxx","Pics","xxxx.png"))
似乎建議您的腳本放在xxxx用戶Downloads目錄的檔案夾中,這意味著資源的相對路徑是Pics/xxxx.png.
基于這些假設,您可以執行以下操作:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369273.html
