"settingsicon.png"
和使用路径 ./x
打开文件,但它不起作用。它说"No such file or directory: './settingsicon.png'"
我在库中尝试它
os
但它不起作用ether.
import os
from PIL import Image
import customtkinter
# Get absolute file path
file_path = os.path.abspath('path/to/settingsicon.png')
# Load image
img = Image.open(file_path)
要么放完整路径,要么在有脚本和图像的目录中执行它。 或者让它在代码中使用脚本的目录,例如:
script_dir = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(script_dir, "settingsicon.png")
settingsicon = customtkinter.CTkImage(dark_image=Image.open(image_path), size=(18, 18))
根据屏幕截图中的代码,这应该有效。
您可以从
__file__
中提取当前脚本的路径,如此处讨论:
https://stackoverflow.com/a/3430395/21012339
这样你就不必每次都
cd
进入文件夹。
如果/当你将你的程序组织成一个包时,还有一种更加pythonic的方式:
from importlib.resources import files
file = files(__package__) / "myfile.xyz"
mytext = file.read_text()
myimage = Image.open(file) #may or may not work without converting to path string
script_dir = os.path.dirname(os.path.abspath(file))
image_path = os.path.join(script_dir, "settingsicon.png")
settingsicon = customtkinter.CTkImage(dark_image=Image.open(image_path), size=(18, 18))
谢谢大家的帮助:)
编辑:删除第 9 行中的拼写错误。
试试这个:
添加这个
ImageTk.PhotoImage
.
片段:
import tkinter as tk
import os
from PIL import ImageTk, Image
root = tk.Tk()
import customtkinter
# Get absolute file path
file_path = 'p1.png'
# Load image
img = ImageTk.PhotoImage(Image.open(os.path.abspath(file_path)))
tk.Label(root, image=img).pack()
root.mainloop()
截图: