首页 > 解决方案 > 从目录读取文件并显示在树查看器表 tkinter

问题描述

我用 treeviewer 构建表,如下所示:

PLS     RF      SVR

我想从特定目录读取文件,并根据文件名,将其显示在正确的列中。例如,如果文件名包含“pls”,则在 PLS 列中显示该文件,然后用户可以选择一个文件。

到目前为止我的代码:(我不知道如何正确地将文件存储在表中)

pred_win=tkinter.Toplevel (window) #create new window
pred_win.title ("predict")
pred_win.geometry ("600x600")
treeView = ttk.Treeview (pred_win)
treeView.grid ()
treeView["columns"] = ["PLS", "SVR","RF"]
treeView["show"] = "headings"
treeView.heading ("PLS", text="PLS")
treeView.heading ("SVR", text="SVR")
treeView.heading ("RF", text="RF")
# get the list of files
path = os.getcwd ()
flist = os.listdir (path)
item_list=[x for x in flist ]

for i in range (len(item_list)):
    treeView.insert ('', 'end', values=item_list[i])

标签: pythonuser-interfacetkinter

解决方案


这可以通过使用轻松完成glob,您可以选择pls末尾或开头或中间的文件(等等..)。如果文件夹列表是:

coolrf.txt
nicerf.txt
pls.txt
hellopls.txt
sitepls.txt
nicesvr.txt
greatsvr.txt
supersvr.txt

那么您的代码将是:

from glob import glob
from itertools import zip_longest # This is needed to loop through 3 lists at the same time
.... # Same code

pls = glob('*pls.*') # Make a list of all files with pls at the end
svr = glob('*svr.*') # Make a list of all files with svr at the end
rf = glob('*rf.*') # Make a list of all files with rf at the end

item_list = item_list = [tup for tup in zip_longest(pls,svr,rf)] # Make a list of tuples of each file type

for i in item_list:
    treeView.insert ('', 'end', values=i) # Insert each tuple on

我们zip_longest()用于同时循环 3 个列表。我们可以使用zip(),但如果 3 的长度不同,那么它不会正确迭代,而zip_longest()会。我们正在将具有字段值的元组插入到树视图中。


推荐阅读