代码之家  ›  专栏  ›  技术社区  ›  Giannis Tsakas

无法在一个tkinter窗口中放置多个图像

  •  1
  • Giannis Tsakas  · 技术社区  · 2 年前
    from tkinter import *
    from PIL import ImageTk, Image
    
    root = Tk()
    nameList = ["images/icons/first.bmp", "images/icons/second.bmp"]
    ycord = 0
    for execute in nameList:
        myimg = ImageTk.PhotoImage(Image.open(execute))
        Label(image=myimg).place(x=0, y=0)
        ycord += 80
    
    root.mainloop()
    

    有了这段代码,出于某种原因 first.bmp 不会显示在tkinter窗口中。只有 second.bmp 确实出现。

    1 回复  |  直到 2 年前
        1
  •  2
  •   acw1668    2 年前

    这是因为你使用相同的变量 myimg

    from tkinter import *
    from PIL import ImageTk, Image
    
    root = Tk()
    nameList = ["images/icons/first.bmp", "images/icons/second.bmp"]
    ycord = 0
    for execute in nameList:
        myimg = ImageTk.PhotoImage(file=execute)
        lbl = Label(root, image=myimg)
        lbl.place(x=0, y=ycord)
        lbl.image = myimg  # use an attribute of label to store the reference of image
        ycord += 80
    
    root.mainloop()