简体   繁体   中英

Image in TreeView not showing Tkinter

I am making a TreeView in Tkinter Python 3.4 I have added a chrome logo but the image never appears.

treeview=ttk.Treeview(frame3)
chromelogo=PhotoImage(file="./Images/minor-logo.png")

chromelogo=chromelogo.subsample(10,10)

treeview.pack(fill=BOTH,expand=True)
treeview.insert('','0','Chrome',text='Chrome', image=chromelogo)

treeview.insert('Chrome','0',"shit",text="shit",image=chromelogo)

treeview.insert('','1','Chrome3',text='Chrome3')

The link for chrome logo: http://logos-download.com/wp-content/uploads/2016/05/Chrome_icon_bright.png

Photoimage doesn't let you open images rather that a gif type if you want to open an image rather than gif in tkinter try the PIL module. you could use any method to install the PIL module, i like the command line

python -m pip install pillow

since you want to your image to feet in the tree view use this to resize and insert it

from tkinter import *
from tkinter import ttk
from PIL import ImageTk,Image
win=Tk()


chromelogo=Image.open("./Images/minor-logo.png")#open the image using PIL
imwidth=10#the new width you want 

#the next three lines of codes are used to keep the aspect ration of the image
wpersent=(imwidth/float(chromelogo.size[0]))
hsize=int(float(chromelogo.size[1])*float(wpersent))#size[1] means the height and the size[0] means the width you can read more about this in th PIL documentation
chromelogo=ImageTk.PhotoImage(chromelogo.resize((imwidth,hsize),Image.ANTIALIAS))# set the width and put it back in the chromelogo variable

treeview=ttk.Treeview(win)
treeview.pack(fill=BOTH,expand=False)
treeview.insert('','0','Chrome',text='Chrome', image=chromelogo)
treeview.image = chromelogo#this one is for telling tkinter not to count the image as garbage
treeview.grid(row=0,rowspan=2,columnspan=2,padx=220,sticky=N+W,pady=20)

chromelogo2=ImageTk.PhotoImage(Image.open("./Images/minor-logo.png"))
treeview.insert('Chrome','0',"shit",text="shit",image=chromelogo2)#here you can also insert the unresized logo so you could see it as big as it is

treeview.insert('','1','Chrome3',text='Chrome3')

win.mainloop()

Simply converting "chromelogo" into a class variable by using the self keyword should fix the problem:

treeview=ttk.Treeview(frame3)
self.chromelogo=PhotoImage(file="./Images/minor-logo.png")

self.chromelogo=self.chromelogo.subsample(10,10)

treeview.pack(fill=BOTH,expand=True)
treeview.insert('','0','Chrome',text='Chrome', image=self.chromelogo)

treeview.insert('Chrome','0',"shit",text="shit",image=self.chromelogo)

treeview.insert('','1','Chrome3',text='Chrome3')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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