python - 从目录读取文件并显示在树查看器表 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])
解决方案
这可以通过使用轻松完成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()
会。我们正在将具有字段值的元组插入到树视图中。
推荐阅读
- javascript - 是否可以为 location.reload() 添加 javascript for/while 循环;
- html - 为什么网站渲染后会自动调用onclick函数-Flask?
- html - 兄弟按钮缩小和增长
- amazon-web-services - AWS Elasticache redis 突然变慢
- sql - 当两列相似而一列不同时如何删除SQL中的重复记录
- parallel-processing - 分发调度程序作业记录的处理
- emacs - 计算数字参数之前的通用参数的数量
- android - Android自定义适配器不显示所有项目
- error-handling - 我需要帮助重构 Rust 中的错误处理
- c - 为什么地址栏中的 UTF-8 Unicode 与 GET 形式在 C 中有所不同?