I am trying to create an explorer in tkinter
. I just heard about an hierarchical Treeview
. Therefore, I am trying to implement it.
Here, I tried using recursion, because for a for
loop, one cannot know the number of subdirectories and files inside a particular folder.
Here is my recursive function.
def new_folder(path,arrs):
for arr in arrs:
if os.path.isdir(path+"\\"+arr):
try:
a1=os.listdir(path+"\\"+arr)
new_folder(path+"\\"+arr,a1)
except PermissionError:
pass
else:
print(path+"\\"+arr)
path="C:\\Users\\91996\\Documents"
arrss=os.listdir(path)
new_folder(path,arrss)
Whenever I run this code, it gives me this error:
Traceback (most recent call last):
File "c:/Users/91996/Documents/Visual studio code/focd.py", line 47, in <module>
new_folder(path,arrss,'item'+str(2))
File "c:/Users/91996/Documents/Visual studio code/focd.py", line 37, in new_folder
new_folder(path+"\\"+arr,a1,values[:-1]+str(3))
File "c:/Users/91996/Documents/Visual studio code/focd.py", line 44, in new_folder
treeview.move(values,'item1','end')
File "C:\Program Files\Python3.8.6\lib\tkinter\ttk.py", line 1388, in move
self.tk.call(self._w, "move", item, parent, index)
_tkinter.TclError: Item item3 not found
Here is my code.
from tkinter import *
import os
# Importing ttk from tkinter
from tkinter import ttk
# Creating app window
app = Tk()
# Defining title of the app
app.title("GUI Application of Python")
# Defining label of the app and calling a geometry
# management method i.e, pack in order to organize
# widgets in form of blocks before locating them
# in the parent widget
ttk.Label(app, text ="Treeview(hierarchical)").pack()
# Creating treeview window
treeview = ttk.Treeview(app)
# Calling pack method on the treeview
treeview.pack()
# Inserting items to the treeview
# Inserting parent
treeview.insert('', '0', 'item1',
text ='Documents')
# Inserting child
i=3
def new_folder(path,arrs,values):
global i
for arr in arrs:
if os.path.isdir(path+"\\"+arr):
try:
a1=os.listdir(path+"\\"+arr)
new_folder(path+"\\"+arr,a1,values[:-1]+str(i))
i+=1
except PermissionError:
pass
else:
treeview.insert(values,'end',text=arr)
print(path+"\\"+arr)
treeview.move(values,'item1','end')
path="C:\\Users\\91996\\Documents"
arrss=os.listdir(path)
new_folder(path,arrss,'item'+str(i))
app.mainloop()
Currently, this is the Treeview
which I made using a for
loop. However, I feel this is not good because it will not fetch files and folders. I had to make 8 nested for
loops to get all files and folders up to the 8th sub-folder. But recursion can solve all the problem. The only problem lies in implementing it with ttk.Treeview
.