繁体   English   中英

Treeview中的第二个图像不刷新tkinter

[英]second image in treeview not refresh tkinter

从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添加图像时...。我可以添加项目,但图像不可见

任何想法?

很常见的问题。 您必须保留图像参考。

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"))

谢谢家伙,将解决方案复制给其他人。 @henry 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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM