【Python】tkinter Treeview控件。不知为何只有在控件放置前,插入控件的图片才有效。【已解决】

我想制作一个选择文件夹,将文件夹内的第一个图片和文件夹名字显示在树栏(第一列),文件夹所在路径显示在列表栏(第二列)。可发现只有在Treeview pack前,插入的Item中的图片才显示或有效。

我在程序目录下放了一个测试图,40*40,一个奇怪的二维码:测试图,40*40,一个奇怪的二维码

from tkinter import *
from tkinter import filedialog
import os
from tkinter import ttk
from PIL import Image, ImageTk


def add_pic():
    global display_dirs_table
    dir_ = filedialog.askdirectory()
    img1_path = os.path.join(dir_, os.listdir(dir_)[1]).replace('\\', '/')
    print(img1_path)
    img1 = Image.open(img1_path)
    imgObj1 = ImageTk.PhotoImage(img1)
    display_dirs_table.insert('', END, text=dir_.split('/')[-1], image=imgObj1,
                              values=(os.path.dirname(dir_),)
                              )
    display_dirs_table.pack(anchor=W, fill=BOTH, expand=True)


root = Tk()
ttk.Style().configure("Treeview", rowheight=80)


root.geometry('700x450')
root_path = os.path.dirname(os.path.abspath(__file__))
find_dirs_button = Button(root, text='浏览', padx=10, pady=5, command=add_pic)


display_dirs_table = ttk.Treeview(root, columns='path')
display_dirs_table.column('#0', anchor=CENTER, stretch=False)
display_dirs_table.column('path', anchor=CENTER)
display_dirs_table.heading('#0', text='名称')
display_dirs_table.heading('path', text='路径')


find_dirs_button.pack(anchor=NE, padx=10, pady=10)


dir_1='fghfd/hgjgfdsf'
img11 = Image.open('1.png')
imgObj11 = ImageTk.PhotoImage(img11)
display_dirs_table.insert('', END, text=dir_1.split('/')[-1], image=imgObj11,
                          values=(os.path.dirname(dir_1),)
                          )

display_dirs_table.pack(anchor=W, fill=BOTH, expand=True)



root.mainloop()

刚运行是这样:
在pack前插入的图片正常显示
在pack前插入的图片正常显示。

点击浏览选择程序所在文件夹后,是这样:
图片路径正常输出,但图片并没有显示
图片路径正常输出,但图片并没有显示。

不知道为什么,慢慢研究,只作记录。
————————————————————————————
已解决。感谢“请叫我问哥”的帮助。
需要在add_pic函数下使imgObj1作用于全局
即 global imgObj1:

def add_pic():
    global imgObj1
    dir_ = filedialog.askdirectory()
    img1_path = os.path.join(dir_, os.listdir(dir_)[1]).replace('\\', '/')
    print(img1_path)
    img1 = Image.open(img1_path)
    imgObj1 = ImageTk.PhotoImage(img1)
    display_dirs_table.insert('', END, text=dir_.split('/')[-1], image=imgObj1,
                              values=(os.path.dirname(dir_),)
                              )
    display_dirs_table.pack(anchor=W, fill=BOTH, expand=True)

否则imgObj1在离开函数后就失效了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值