python 照片图像不会显示在tkinter树视图中

mum43rcc  于 2023-01-01  发布在  Python
关注(0)|答案(3)|浏览(174)

我正在尝试在tkinter树视图中显示一个图像。我一直在阅读可能的解决方案,但似乎都不起作用,我一直得到一个只有列标题的空树。对于我一直在阅读的内容,我必须保留对PhotoImage的引用,但无论我如何尝试,它都不会发生。下面是一个简单的代码示例:

```import tkinter as tk
from tkinter import ttk
from PIL import ImageTk as itk
import PIL.Image
import io

s= tk.Tk()
s.title('No *£/**@#* image showing')
s.geometry('400x400')

s.rowconfigure(1, weight = 1)

s.columnconfigure(1,weight=1)

headings=['Image']

p = '032f8072.gif'
img1 = PIL.Image.open('032f8072.gif')
#img1 = img1.resize((10,10))
img = itk.PhotoImage(img1)

tree = ttk.Treeview(s)
tree.grid(column=1,row=1,sticky='NSEW')
tree['columns']=headings
tree['show']='headings'
for i in headings:
    tree.heading(i,text=i)
    
tree.column(0, width=125,stretch=True)
#tree.column(1, width=125,stretch=True)

tree.insert('','end','0', open =True, image= img)
tree.image = img

s.mainloop()```

我试过使用. gif和. png,我试过一起或单独使用PIL. Image和Imagetk. PhotoImage,我也试过将img保存在一个列表中,以便从列表中调用,以避免丢失引用。
我真的需要得到这一小段代码的权利,我真的很沮丧,这一小段阻碍我。我真的很感激,如果有人能帮助我。
亲切问候

js4nwp54

js4nwp541#

这花了一段时间才弄清楚!我最终找到了10个月前一个类似问题的答案(不是正式的答案,但可以在问题下的评论中查看):Treeview Image not displaying
用户说这个注解解决了他们的问题,所以我试着将它应用到您的示例中。注解行的意思是tree['show'] = 'headings'强制Treeview只显示标题,而不显示树的主体。要解决这个问题,请将该行替换为以下内容:
tree['show'] = ('headings', 'tree')
来显示整棵树,图像应该开始显示。

ia2d9nvy

ia2d9nvy2#

您可以使用tree['columns']创建列,但是正如ne0n p1atypus所说,您不能使用tree['show']显示它们。您仍然可以使用explorer_tree手动输入列的名称。(“#0”,text=“Image”,锚= 'center')注意,“#0”指的是将显示图像的列。我没有尝试使用for循环输入列名。另外,当试图使用for循环构造一个树形视图来显示不同行中的图像时,这个算法必须在定义树形视图的函数中,并且所有的PhotoImage对象必须被附加到一个列表中以保持其引用,否则它们将被作为垃圾收集。我将在下面留下一个示例。

global eow
    global dffile
    global temp_result
    global explorer_tree
    #Define window and treeview
    explorer_headings = ["Name",'Code', 'Supplier Code']
    temp_list=[]
    
    eow= Toplevel(acm)
    eow.title('Stock Explorer')
    eow.geometry('400x650')
    eow.geometry("+0+0")
    eow.minsize(400,650)
    eow.state('zoomed')
                    
    eow.grab_set()
    
    #style
    style2 = ttk.Style()
    style2.theme_use("awdark")
    style2.configure("2style.Treeview.Heading",font=('Calibri', 18,'bold')) # Modify the font of the headings
    style2.configure("2style.Treeview", font=('Calibri', 20),rowheight=100)
    eow['bg']='black'
    
    #Columns and rows
    eow.columnconfigure(0, weight=1)
    eow.columnconfigure(1, weight =2)
    eow.columnconfigure(2, weight =2)
    eow.columnconfigure(3, weight =1)
    
    eow.rowconfigure(1, weight=4)
    eow.rowconfigure(2, weight=2)
    eow.rowconfigure(3, weight=2)
    eow.rowconfigure(4, weight=2)
    eow.rowconfigure(5, weight=1)

    #Treeview to display data
    explorer_tree = ttk.Treeview(eow, style='2style.Treeview',height=3)
    explorer_tree.grid(column=1,row=2,sticky='NSEW', columnspan=2, rowspan=2)

    #treeview scrollbars
    xscroll_file_data= tk.Scrollbar(eow, orient='horizontal', command= explorer_tree.xview)
    yscroll_file_data= tk.Scrollbar(eow, orient='vertical', command= explorer_tree.yview)
    xscroll_file_data.grid(column=1,row=5,sticky='NEW',columnspan=2)
    yscroll_file_data.grid(column=3,row=2,sticky='WNS',rowspan= 3)
    explorer_tree.configure(yscrollcommand=yscroll_file_data.set)

    add_part_button = Button(eow, text='Add Part',font=('Calibri', 14,'bold'), 
                          activebackground='white', activeforeground='black',relief='raised', borderwidth=5
                            , command = add_part_from_pic_list)
    add_part_button.grid(column=1, row=5, sticky='NSEW', padx=100, pady=40)
    
    notfound_button = Button(eow, text='Part Not In List',font=('Calibri', 14,'bold'), 
                          activebackground='white', activeforeground='black',relief='raised', borderwidth=5)
    notfound_button.grid(column=2, row=5, sticky='NSEW', padx=100, pady=40)
    
    code_label = Label(eow, text='Code: '+str(code)+'  Name: '+online_name,background='black',
                       foreground='white',font=('Calibri', 18))
    code_label.grid(column=1,row=1, sticky = 'NSEW',pady=10, padx=20)
    #Name the headings
    explorer_tree['columns']=explorer_headings
    explorer_tree.heading("#0",text="Image",anchor= 'center')
    explorer_tree.heading(0,text="Name",anchor= 'center')
    explorer_tree.heading(1,text="Code",anchor= 'center')
    explorer_tree.heading(2,text="Supplier Code",anchor= 'center')
    #Format the columns
    explorer_tree.column('#0', width=130,stretch=False)
    explorer_tree.column(0,width=200, anchor='center',stretch=True)
    explorer_tree.column(1,width= 200, anchor='center', stretch=False)
    explorer_tree.column(2, anchor='center',stretch=False)

    explorer_tree.tag_configure('even',foreground='black',background='white')
    children = explorer_tree.get_children()

    eow.protocol("WM_DELETE_WINDOW",Instant_exit)
    explorer_tree.bind("<Double-1>", add_part_from_pic_list)
#construct tree
    temp_list=[]
    for i in range(len(temp_result)):
        for j in range(len(dffile['Name'])):
            if temp_result[i] == dffile['Name'][j]:
                children1 = explorer_tree.get_children()
                temp_row = [dffile['Name'][j],dffile['Code'][j],dffile['Supplier Code'][j]]
                p = temp_row[1]+".png"
                pp = "images/"+temp_row[1]+".png"
                np = 'images/noimage.png'
                try:#Append the PhotoImage object to a list rather than to a variable This will avoid the image being collected as garbage
                  temp_list.append(ImageTk.PhotoImage(Image.open(pp).resize((100,100),Image.ANTIALIAS)))
                except FileNotFoundError:
                    
                    temp_list.append(ImageTk.PhotoImage(Image.open(np).resize((100,100),Image.ANTIALIAS)))
                    continue
              
                if len(children1)%2 == 0: #When calling the image for tree.insert, call the image from the list i.e. temp_list[i]
                    explorer_tree.insert('','end',iid=(len(children1)), image=temp_list[i], values=(temp_row[0],temp_row[1],
                                        temp_row[2]),tags=('even'))

                else:
                    explorer_tree.insert('','end',iid=(len(children1)), image=temp_list[i], values=(temp_row[0], temp_row[1],
                                        temp_row[2]),tags=('odd'))    
    eow.mainloop() ```
htrmnn0y

htrmnn0y3#

试试这个,对我来说管用。

粗体表示重要更改。

树= ttk.树视图(主视图=画布,列=汽车标题,显示=“树标题”,高度=11)
img = tk.照片图像(文件=r“帧/图像/图像. gif”)
插入(父项="",索引=“结束”,图像=img,文本=“信息”,值=集合树[i],标签=(“奇数行”))

标记标签图像= img

相关问题