树视图中的第二个图像未刷新

2024-05-08 02:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

从def向treeview添加一个图像时出现问题

案例一-没问题

import tkinter
import PIL.Image, PIL.ImageTk
from tkinter import PhotoImage
from tkinter import ttk    
window = tkinter.Tk()
tree = ttk.Treeview(window)
tree["columns"]="one"
tree.heading("#0",text="Item",anchor=tkinter.W)
tree.heading("one", text="Detections",anchor=tkinter.W)
style = ttk.Style(window)
style.configure('Treeview', rowheight=50)
tree.grid(row=0,column=0,sticky=tkinter.N)
img = PIL.Image.open("1.jpg")
img = img.resize((10, 10))                
img = PIL.ImageTk.PhotoImage(img)
tree.insert('', 'end', text="predict", image=img, value=("title"))

案例二-不起作用

window = tkinter.Tk()
tree = ttk.Treeview(window)
tree["columns"]="one"
tree.heading("#0",text="Item",anchor=tkinter.W)
tree.heading("one", text="Detections",anchor=tkinter.W)
style = ttk.Style(window)
style.configure('Treeview', rowheight=50)
tree.grid(row=0,column=0,sticky=tkinter.N)
#img = PIL.Image.open("2.jpg")
#img = img.resize((10, 10))                
#img = PIL.ImageTk.PhotoImage(img)
#tree.insert('', 'end', text="predict", image=img, value=("title"))

def snapshot():
    img = PIL.Image.open("2.jpg")
    img = img.resize((10, 10))
    img = PIL.ImageTk.PhotoImage(img)
    tree.insert('', 'end', text="predict2", image=img, value=("title2"))

btn_snapshot=tkinter.Button(window, text="Snapshot", width=50, command=snapshot)    
btn_snapshot.grid(row=1,column=0)

那么,问题是当从def添加图像时。。。。我可以添加项目,但图像不可见

你知道吗


Tags: textimageimporttreeimgpiltkinterwindow
2条回答

很常见的问题。你必须保留一个图像参考

def snapshot():
    img = PIL.Image.open("2.jpg")
    img = img.resize((10, 10))
    img = PIL.ImageTk.PhotoImage(img)
    tree.img2dotjpg = img # store the reference
    tree.insert('', 'end', text="predict2", image=img, value=("title2"))

谢谢你,伙计,为别人复制解决方案。 @Yik,你是对的,重要的是把所有的图像都放在函数之外的列表中

list_img = []
def snapshot():
    img = PIL.Image.open("frame-01-07-2019-22-02-38.jpg")
    img = img.resize((10, 10))
    img = PIL.ImageTk.PhotoImage(img)
    list_img.append(img)    
    tree.insert('', 'end', text="predict2", image=list_img[len(list_img)-1], value=("title2"))

相关问题 更多 >