我正在制作一个GUI,它将文件夹或文件从源文件复制到目的地。我需要使用复选框制作目录树结构来浏览文件。我提到了这个How to create a tree view with checkboxes in Python,但我找不到创建整体的逻辑文件夹。 请帮我解决这个问题。
from tkinter import tix
import os
i = 0
class View(object):
def __init__(self, root,path):
self.root = root
self.path = path
self.makeCheckList(self.path)
def makeCheckList(self,path1):
global i
self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
self.cl.pack(fill='both',expand="yes")
self.cl.hlist.add("CL1", text=path1)
self.cl.setstatus("CL1", "off")
self.check(path1)
self.cl.autosetmode()
def selectItem(self, item):
print (item, self.cl.getstatus(item))
def check(self,path1):
global i
self.path1 = path1
file = os.listdir(path1)
for p in file:
#print(p)
full_path = path1 +"\\"+ p
val = "CL1.Item1"
if os.path.isdir(full_path) != True :
self.cl.hlist.add("CL1.Item"+ str(i), text=p)
self.cl.setstatus("CL1.Item"+str(i), "off")
i = i + 1
self.dir(path1)
def dir(self,path1):
global i
self.path1 = path1
file = os.listdir(path1)
for folder in file:
full_path = path1 +"\\"+ folder
if os.path.isdir(full_path) == True :
self.cl.hlist.add("CL1.Item"+str(i), text=folder)
self.cl.setstatus("CL1.Item"+str(i), "off")
i = i + 1
#self.dir(full_path)
def main():
root = tix.Tk()
root.geometry("800x400")
view = View(root,"C:\\")
root.update()
root.mainloop()
if __name__ == '__main__':
main()
我的逻辑在这里不正确。我想要一个递归函数,它将创建整个目录
答案 0 :(得分:2)
如果要创建目录内容的树,确实需要递归函数。对于目录的每个元素,首先将其放在树中,然后,如果是目录,则重新应用该函数:
def check(self, parent, path):
content = os.listdir(path)
for i, item in enumerate(content):
full_path = os.path.join(path, item) # item absolute path
entry = "{}.Item{}".format(parent, i) # item path in the tree
self.cl.hlist.add(entry, text=item) # add item in the tree
self.cl.setstatus(entry, "off")
if os.path.isdir(full_path):
# reapply the function if the item is a directory
self.check(entry, full_path)
在这个函数中,我需要跟踪树目录中的父目录绝对路径及其路径。
然后,要生成树,请使用makeCheckList
方法:
def makeCheckList(self): # no need of any extra argument here
self.cl = tix.CheckList(self.root, browsecmd=self.selectItem)
self.cl.pack(fill='both',expand="yes")
# add the root directory in the tree
self.cl.hlist.add("CL1", text=self.path)
self.cl.setstatus("CL1", "off")
# build the tree
self.check("CL1", self.path)
self.cl.autosetmode()
如果你使用python 3.5或更高版本,你可以用os.listdir
替换os.scandir
来加速你的程序:
def check(self, parent, path):
with os.scandir(path) as content:
for i, item in enumerate(content):
entry = "{}.Item{}".format(parent, i)
self.cl.hlist.add(entry, text=item.name)
self.cl.setstatus(entry, "off")
if item.is_dir():
self.check(entry, item.path)