【问题标题】:Image in TreeView not showing TkinterTreeView 中的图像未显示 Tkinter
【发布时间】:2018-03-12 08:34:21
【问题描述】:

我正在 Tkinter Python 3.4 中制作 TreeView 我添加了一个 chrome 徽标,但图像从未出现。

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

镀铬标志链接:http://logos-download.com/wp-content/uploads/2016/05/Chrome_icon_bright.png

【问题讨论】:

    标签: python tkinter treeview


    【解决方案1】:

    如果您想在 tkinter 中打开图像而不是 gif,Photoimage 不允许您打开图像而不是 gif 类型,请尝试 PIL 模块。你可以使用任何方法来安装 PIL 模块,我喜欢命令行

    python -m pip install pillow
    

    因为你想你的图像在树视图中的英尺使用它来调整大小并插入它

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

    【讨论】:

    • 我打开画图保存为 gif 改变了图像路径 aas ./Images/chrome.gif 仍然没有效果
    • 还有什么建议吗?
    【解决方案2】:

    只需使用 self 关键字将“chromelogo”转换为类变量即可解决问题:

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

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多