使用可滚动条为tkinter创建图像列表

时间:2018-04-17 08:46:26

标签: tkinter

我知道如何创建图像以及可滚动的列表框,但是当我将这两个元素组合在一起时它不起作用。有任何实现它的想法吗?

import tkinter as tk
from PIL import ImageTk, Image


class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        text = tk.Text(self, wrap="none")
        vsb = tk.Scrollbar(orient="vertical", command=text.yview)
        text.configure(yscrollcommand=vsb.set)
        vsb.pack(side="right", fill="y")
        text.pack(fill="both", expand=True)

        for i in range(20):
            # b = tk.Button(self, text="Button #%s" % i)
            photo = tk.PhotoImage(file='img.png')
            photo = photo.subsample(2)

            b = tk.Label(self,image=photo)
            # b.pack(side='bottom',fill='x')
            text.window_create("end", window=b)
            text.insert("end", "\n")

        text.configure(state="disabled")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

如果

,它可以查看图像列表
b = tk.Label(self,image=photo)

变成这个

b = tk.Label(self,text='test')

1 个答案:

答案 0 :(得分:1)

每个图像对象都必须保留引用。 可以通过添加

来解决问题
b = tk.Label(self,image=photo)
b.image = photo # keep a reference

详情可参考here

相关问题