请教下各位tkinter怎么用for循环显示图片?

由于用for循环界面只会显示一张图,很是气人。
下面的代码是想要显示的4张图,如果用for的话,怎样可以方便的写出并且实现效果?
如果直接这样,

python">    image_size=(150,150)

fm1=tk.Frame(window)

files=['candy.jpg','mosaic.jpg','rain-princess.jpg','udnie.jpg']

for file in files:

img1 = Image.open(f'./images/style-images/{file}')

img1 = img1.resize(image_size, Image.ANTIALIAS)

img1 = ImageTk.PhotoImage(img1)

tk.Label(fm1, image=img1).pack(side=tk.RIGHT, padx=10)

其效果是这样的:

请教下各位tkinter怎么用for循环显示图片?

目前我四个图片都显示,就用下面的代码,copy了四次,但是怎么直接用for来写呢?

    image_size=(150,150)

fm1=tk.Frame(window)

files=['candy.jpg','mosaic.jpg','rain-princess.jpg','udnie.jpg']

img1 = Image.open(f'./images/style-images/{files[0]}')

img1 = img1.resize(image_size, Image.ANTIALIAS)

img1 = ImageTk.PhotoImage(img1)

tk.Label(fm1, image=img1).pack(side=tk.RIGHT,padx=10)

img2 = Image.open(f'./images/style-images/{files[1]}')

img2 = img2.resize(image_size, Image.ANTIALIAS)

img2 = ImageTk.PhotoImage(img2)

tk.Label(fm1, image=img2).pack(side=tk.RIGHT, padx=10)

img3 = Image.open(f'./images/style-images/{files[2]}')

img3 = img3.resize(image_size, Image.ANTIALIAS)

img3 = ImageTk.PhotoImage(img3)

tk.Label(fm1, image=img3).pack(side=tk.RIGHT, padx=10)

img = Image.open(f'./images/style-images/{files[3]}')

img = img.resize(image_size, Image.ANTIALIAS)

img = ImageTk.PhotoImage(img)

tk.Label(fm1, image=img).pack(side=tk.RIGHT, padx=10)

fm1.pack()


回答:

这样写,多家一个img_list保留img对象。

image_size=(150,150)

img_list=[]

fm1=tk.Frame(window)

files=['candy.jpg','mosaic.jpg','rain-princess.jpg','udnie.jpg']

for file in files:

img1 = Image.open(f'./images/style-images/{file}')

img1 = img1.resize(image_size, Image.ANTIALIAS)

img1 = ImageTk.PhotoImage(img1)

img_list.append(img1)

tk.Label(fm1, image=img1).pack(side=tk.RIGHT,padx=10)

fm1.pack()

以上是 请教下各位tkinter怎么用for循环显示图片? 的全部内容, 来源链接: utcz.com/a/161855.html

回到顶部