Yonggie
2020-04-15 21:58
采纳率: 100%
浏览 621

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

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

    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)

其效果是这样的:

图片说明

目前我四个图片都显示,就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()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 陈年椰子 2020-04-16 09:18
    已采纳
    
    imglist = []
    for i in range(len(files)):
        file = files[i]
        img1 = Image.open(r'./image/{}'.format(file))
        img1 = img1.resize(image_size, Image.ANTIALIAS)
        img1 = ImageTk.PhotoImage(img1)
        imglist.append(img1)
        tk.Label(window, image=imglist[i]).pack(side=tk.RIGHT, padx=10)
    
    
    点赞 2 打赏 评论
  • zhouhongkai1 2021-07-18 20:45

    问题就在 tk.Label(window, image=imglist[i]).pack(side=tk.RIGHT, padx=10)
    四个图片显示在一个位置,导致重叠

    点赞 打赏 评论

相关推荐 更多相似问题