我试图在我的列表中使用不同项目的tkinter单选按钮中的图像。For循环运行良好。在为每个项目生成变量路径时,刚刚获得PhotoImage错误。
from tkinter import *
from PIL import Image, ImageTk
win = Tk()
win.title("Review demo")
win.geometry("900x600")
win.minsize(900, 600)
win.maxsize(900, 600)
choices = ["like", "dislike", "love", "garbage"]
x = IntVar()
img = StringVar() # img declaration doesn't work
for r in range(len(choices)):
item_name = choices[r]
path = item_name+".png"
img = PhotoImage(file = path )
# img = PhotoImage(file = item_name+'.png')
radiobtn = Radiobutton(win,
text=item_name,
variable=x,
value=r,
padx=20,
pady=20,
image= img
)
radiobtn.pack(anchor=E)
win.mainloop()
error is
img = PhotoImage(file = item_name+'.png')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRohitAppDataLocalProgramsPythonPython311Libtkinter__init__.py", line 4130, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:UsersRohitAppDataLocalProgramsPythonPython311Libtkinter__init__.py", line 4075, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "like.png"
我认为即使有ImageTk的帮助,我们也不能在循环内使用PhotoImage。所以我们创建了一个单独的图像列表路径
choice_images = []
for choice in choices:
image = Image.open(choice+'.png')
resized_image = image.resize((100, 100))
final_image = ImageTk.PhotoImage(resized_image)
choice_images.append(final_image)
# generating radio buttons with respective images
x = IntVar()
for r in range(len(choices)):
radiobtn = Radiobutton(win,
text=choices[r],
variable=x,
value=r,
font=("Noto Sans", 20),
image= choice_images[r],
compound= 'right',
command=rate_item
)
radiobtn.pack(anchor=E)
由于您使用相同的变量img
来保存图像的引用,因此只有最后一个图像在for循环之后具有变量引用它,并且之前的图像被垃圾收集。
您可以使用单选按钮的属性来存储图像的引用,如下所示:
for r in range(len(choices)):
item_name = choices[r]
path = item_name+".png"
# use ImageTk.PhotoImage instead of PhotoImage
# to support latest PNG format
img = ImageTk.PhotoImage(file=path)
radiobtn = Radiobutton(win,
text=item_name,
variable=x,
value=r,
padx=20,
pady=20,
image=img
)
radiobtn.pack(anchor=E)
radiobtn.image = img # save the reference of the image