I'm having trouble writing a function that could take a list of tarfile items via the .getmembers()
method and put them in a proper tree structure (files within folders and subfolders) in the Treeview widget. I found a post similar to what I wanted: Tkinter: Treeview widget, but I just couldn't get it adapted for viewing archives.
The problem with the solution I referenced is that it uses os
to walk a given directory and insert the items into a Treeview. Of course that won't work on a tarfile because it's a file, not a folder so when I tried modifying the solution I stored the tarfile members in a list and tried to feed it through the function but it's just not working for me.
Essentially, I need help with writing a function that takes a list of directory and file names and can insert parent directories into the root of the treeview, and child items into their containing folders.
import os
import tkinter as tk
import tkinter.ttk as ttk
import tarfile
window = tk.Tk()
window.title("Testing")
window.geometry("500x500")
tree = ttk.Treeview(window)
tree.pack()
tree.heading('#0', text="Item")
tree.column('#0', width=495)
# Get TAR items
with tarfile.TarFile("testing.tar") as topen:
tarlist = topen.getmembers()
# Get our first directory in the list and remove it from stack
for i in tarlist:
if i.isdir() == True:
start_node = i.name
del tarlist[tarlist.index(i)]
break
# Insert root folder
root_node = tree.insert('', 'end', text=start_node)
def insert():
# Go through the rest of the member list and put the member in the proper place
# within the tree structure
window.mainloop()
The idea is to use the full item's path as its iid in the tree so that you can get both the item's parent and the item's label with parent, label = os.path.split(item.path)
.
According to .getmembers()
docstring,
Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive.
So you don't need to worry about the existence parent, it will have been created before if you go through tarlist
with a for loop, like in the code below.
import os
import tkinter as tk
import tkinter.ttk as ttk
import tarfile
window = tk.Tk()
window.title("Testing")
window.geometry("500x500")
tree = ttk.Treeview(window)
tree.pack()
tree.heading('#0', text="Item")
tree.column('#0', width=495)
# Get TAR items
with tarfile.TarFile("testing.tar") as topen:
tarlist = topen.getmembers()
def insert():
for item in tarlist:
parent, label = os.path.split(item.path)
tree.insert(parent, 'end', iid=item.path, text=label)
insert()
window.mainloop()