tkinter:为什么图像显示不正确

时间:2014-12-09 23:19:06

标签: python python-3.x tkinter

代码:

from tkinter import *

root = Tk()

f1=Frame(root)
for img,rlf in [ ('woman',RAISED),('mensetmanus',SOLID),
    ('terminal',SUNKEN), ('escherknot',FLAT),
    ('calculator',GROOVE),('letters',RIDGE)]:
        filename = img + ".gif"
        img1 = PhotoImage(file= filename)
        Label(f1, image = img1, relief=rlf).pack(side=LEFT,
            padx=5)
f1.pack()

root.mainloop()

你能帮我理解为什么这个摘录会为图像产生5个空位(尽管边框是根据所指的正确绘制的)和1个图像。最后一张图片(可见)是字母。它似乎是从它的实际大小裁剪而来。我的letters.gif包含从A到G的字母,但此代码仅显示从半B到一半F.

1 个答案:

答案 0 :(得分:1)

我认为它不起作用,因为在每个循环中都会覆盖img1。您需要在某处保留对图像对象的引用,以便垃圾收集器不会丢弃它们:

from tkinter import *

root = Tk()

f1=Frame(root)
img_list = []                  #<-- store references to images
for img,rlf in [ ('woman',RAISED),('mensetmanus',SOLID),
    ('terminal',SUNKEN), ('escherknot',FLAT),
    ('calculator',GROOVE),('letters',RIDGE)]:
        filename = img + ".gif"
        img1 = PhotoImage(file= filename)
        img_list.append(img1) #<-- store references to images
        Label(f1, image = img1, relief=rlf).pack(side=LEFT,
            padx=5)
f1.pack()

root.mainloop()