2015-10-14 141 views
1

我试图通过一个循环与TKinter创建多个按钮,但是当我运行脚本时,5个按钮类对象被创建,但只有最后一个行为作为一个button.with TKimage,即时尝试覆盖图片来自每个按钮上的字典中的url。但字典包含5个图像,只有最后一个按钮变成了实际的按钮,并且具有5个图像的最后一个。无法通过tkinter for循环创建按钮。 (Python)

这是我的代码:

film = films_dict['filmsoptv']["film"]             #<<<< voor plaatjes films in TkinterGUI 
Buttons = ['Button1','Button2','Button3','Button4','Button5'] 
lijstnummers = [1,2,3,4,5] 
for film, i, j in zip((films_dict['filmsoptv']["film"]),(lijstnummers),(Buttons)): 
    image_bytes = urlopen(film["cover"]).read() 
    data_stream = io.BytesIO(image_bytes) 
    pil_image = Image.open(data_stream) 
    tk_image = ImageTk.PhotoImage(pil_image) 
    j = Button(window,command=close,height=296,width=200,image=tk_image) 
    j.grid(row=0, column=i) 

films_dict包含5个子字典我,通过调用它在一个for循环,通过滚动访问子词典的封面的URL。 films_dict每天都在变化,所以我不能使用被动网址。

任何人可以帮助我创建5个按钮而不是一个?

回答

1

只是一个猜测,但我认为除最后一张图像外都是garbage collected,因为只有最后一张图像的引用(tk_image仍指向循环后的那张)。出于某种原因,在Button或标签中使用的图像不会被视为垃圾收集器的引用。尝试将引用存储到全部列表或字典中的图像,然后它应该工作。

此外,它似乎想要将按钮添加到列表Buttons通过将其分配给j。但这不起作用。更好地将Buttons初始化为空列表,并将append新的Button初始化为该列表。试试这个(未测试):

images = [] 
buttons = [] 
for i, film in enumerate(films_dict['filmsoptv']["film"], 1): 
    image_bytes = urlopen(film["cover"]).read() 
    data_stream = io.BytesIO(image_bytes) 
    pil_image = Image.open(data_stream) 
    tk_image = ImageTk.PhotoImage(pil_image) 
    j = Button(window, command=close, height=296, width=200, image=tk_image) 
    j.grid(row=0, column=i) 
    images.append(tk_image) 
    buttons.append(j)