【问题标题】:Having trouble creating buttons with a for-loop through tkinter. (Python)通过 tkinter 使用 for 循环创建按钮时遇到问题。 (Python)
【发布时间】:2016-01-12 09:42:08
【问题描述】:

我试图通过使用 TKinter 的循环创建多个按钮,但是当我运行脚本时,会创建 5 个类似按钮的对象,但只有最后一个充当按钮。使用 TKimage,我试图覆盖出现的图片从每个按钮上的字典中的 url。但是字典包含 5 张图片,只有最后一个按钮变成了实际的按钮,并且上面有 5 张图片中的最后一个。

这是我的代码:

    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 个按钮而不是一个?

【问题讨论】:

    标签: python button for-loop dictionary tkinter


    【解决方案1】:

    只是一个猜测,但我认为除了最后一张图片之外的所有图片都是garbage collected,因为只有最后一张图片的引用(tk_image 在循环之后仍然指向那个图片)。出于某种原因,在 Button 或 Label 中使用的图像不算作垃圾收集器的引用。尝试将对所有图像的引用存储在列表或字典中,然后它应该可以工作。

    此外,您似乎希望将 Button 添加到列表 Buttons,方法是将其分配给 j。但是,这行不通。最好将Buttons 初始化为空列表,并将append 新按钮初始化为该列表。试试这个(未测试):

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2012-04-10
      • 2017-06-02
      相关资源
      最近更新 更多