【问题标题】:second image in treeview not refresh tkinter树视图中的第二个图像不刷新 tkinter
【发布时间】:2019-07-02 04:26:08
【问题描述】:

我在将一张图片从 def 添加到树视图时遇到问题

案例一 - 没关系

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

有什么想法吗?

【问题讨论】:

  • 如果您有超过 1 张图像 - 将它们附加到函数之外的列表中。

标签: python tkinter


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多