我想制作一个选择文件夹,将文件夹内的第一个图片和文件夹名字显示在树栏(第一列),文件夹所在路径显示在列表栏(第二列)。可发现只有在Treeview pack前,插入的Item中的图片才显示或有效。
我在程序目录下放了一个测试图,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前插入的图片正常显示。
点击浏览选择程序所在文件夹后,是这样:
图片路径正常输出,但图片并没有显示。
不知道为什么,慢慢研究,只作记录。
————————————————————————————
已解决。感谢“请叫我问哥”的帮助。
需要在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在离开函数后就失效了