Python TKinter:在For循环后调整画布中缩略图的大小
在一个文件夹中,我有256个图像。我将它们作为带有for循环的缩略图加载。 我想点击其中一个,然后在画布上放大 我使用的代码是:Python TKinter:在For循环后调整画布中缩略图的大小,python,tkinter,Python,Tkinter,在一个文件夹中,我有256个图像。我将它们作为带有for循环的缩略图加载。 我想点击其中一个,然后在画布上放大 我使用的代码是: A = Canvas(my_frame1, bg="blue", height=650, width=650) A.grid(row=0, column=0, sticky=NW) B = Canvas(my_frame1, bg="green", height=550, width=550) B.grid(row=0, col
A = Canvas(my_frame1, bg="blue", height=650, width=650)
A.grid(row=0, column=0, sticky=NW)
B = Canvas(my_frame1, bg="green", height=550, width=550)
B.grid(row=0, column=1, sticky=NW)
C = Canvas(my_frame1, bg="white", height=256, width=256)
C.grid(row=0, column=2, sticky=NW)
def several():
val_x=x.get()
image_id = C.create_image(0, 0, anchor='nw', image=img_list[val_x-1])
img_list=[]
path = "./gfx"
n_row = 0
n_col = 0
index = 0
x = IntVar()
for f in os.listdir(path):
img_list.append(ImageTk.PhotoImage(Image.open(os.path.join(path,f))))
n_col +=1
index +=1
if n_col > 9:
n_row +=1
n_col = 1
tile = Radiobutton(A, image=img_list[index-1], indicatoron=0, bd=2, variable = x, value = index, selectcolor="red", command=several)
tile.grid(row=n_row, column = n_col)
root.mainloop()
此代码可以工作,但不会调整图像大小
我试过:
def several():
val_x=x.get()
img_a=img_list[val_x-1]
img_b = img_a.resize((256, 256), Image.ANTIALIAS)
img_c = ImageTk.PhotoImage(img_b)
image_id = C.create_image(0, 0, anchor='nw', image=img_c)
C.itemconfig(image_id)
我得到了这个错误:
****Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\me\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\me\Desktop\python_edit_binary\test.py", line 52, in several
img_b = img_a.resize((256, 256), Image.ANTIALIAS)
AttributeError: 'PhotoImage' object has no attribute 'resize'****
我做错了什么
编辑 经过一些研究,我写了这段代码,但很奇怪:
def several():
val_x=x.get()
img_canvas = []
for f in os.listdir(path):
img_canvas.append(Image.open(os.path.join(path,f)))
img_a=(img_canvas[val_x-1])
img_b = img_a.resize((256, 256), Image.ANTIALIAS)
img_c = ImageTk.PhotoImage(img_b)
image_id = C.create_image(0, 0, anchor='nw', image=img_c)
C.itemconfig(image_id)
print(img_id)
正如我所说的,它工作得非常完美:图像的大小被调整并显示在画布上!!!但是我也得到了一个错误,因为我把打印(图像id)错放在打印(图像id)中了
NameError: name 'img_id' is not defined
如果我删除命令打印(img_id)或更正它,图像将不再显示
我也尝试过其他解决方案,只要我产生了错误,代码就可以工作
这太奇怪了,不是吗?我试着编辑我的帖子以向大家致意,但我的修改没有保存。。。抱歉。正如错误所说,
PhotoImage()
没有resize()
函数。您需要在Image.open(…)
的实例上调用它。这是否回答了您的问题?你好我已经阅读了该线程,但无法将函数Image.open()用于我的图像列表。