File browser with column sorting


File browser with column sorting
Pandas DataFrame in Tkinter Treeview Sorting of Treeview columns
User can click the header and update the view by sorting the rows in the selected column order.

Tkinter window layout

Inside the window All details of the directory including file name, file type, date of Modification and file size are displayed using a Treeview.
Here we have used Filedialog to create the dialog box for user to select directory.

Button b1 : On click of this Button the function my_fun() is called.
lb1 : Label to show the user selected path

Functions used

my_select: Show the file dialog box to select a directory.
my_treeview : Create the Structure of the Treeview without any rows.
my_details : Reads the file details of the selected directory and creates the DataFrame.
my_upd : Add rows to treeview from the DataFrame
my_sort : Sort the DataFrame based on user click and call my_upd() to refresh the view.

my_select() : Select the directory

This function is calle on click of the button b1.
def my_select():  # Select directory 
    my_dir = filedialog.askdirectory() # dialog box to select directory 
    lb1.config(text=my_dir) # update the text of Label with directory path
    my_treeview(my_dir) # call function with path 

my_treeview(): Add treeview to window

The Treeview trv structure part is added to the window. Click event is added to all headers to call the function my_sort() with name of the column as parameter.
def my_treeview(path):
    global trv
    trv = ttk.Treeview(my_w, selectmode ='browse',show='headings')
    trv.grid(row=2,column=1,columnspan=3,padx=30,pady=10)
    # column identifiers 
    trv["columns"] = ("1", "2","3","4")
    trv.column("1", width = 150, anchor ='w')
    trv.column("2", width = 100, anchor ='c')
    trv.column("3", width = 100, anchor ='c')
    trv.column("4", width = 70, anchor ='c')

    trv.heading(1, text ="Name",anchor='w',command=lambda :my_sort('Name'))
    trv.heading(2, text ="Type",anchor='c',command=lambda :my_sort('Type'))
    trv.heading(3, text ="Date Modified",anchor='c',command=lambda :my_sort('Date'))
    trv.heading(4, text ="Size",anchor='c',command=lambda :my_sort('Size'))
        
    my_details(path) # Pass the path to create dataframe

my_details() : Create DataFrame with file details

Using the os library all details of the selected directory is collected and inserted to the DataFrame df.
def my_details(path): # Create the DataFrame with file details 
    global df
    l1=['Name','Type','Date','Size'] # column names 
    df = pd.DataFrame(columns=l1) # add columns to DataFrame
    files=os.listdir(path)
    for f in files:
        f_path=path+'\\'+f # Path with file name
        t_stamp=os.path.getmtime(f_path) # for file modificaton time
        #t_stamp=os.path.getctime(path) # for file Creation time
        f_name,f_extension=os.path.splitext(f_path) # get file extension
        size=os.path.getsize(f_path) # size of file in bytes 
        dt_mod = datetime.fromtimestamp(t_stamp) # date object 
        #print('File Modified on:', dt_mod)  # Prting date and time 
        m_date = datetime.strftime(dt_mod, '%Y-%m-%d') # Change format 
        #print(f, f_extension, m_date,size)
        my_list=[f,f_extension,m_date,size] # List with file data
        df.loc[len(df)]=my_list # adding list to DataFrame
    my_upd()

my_upd() : Adding DataFrame rows to Treeview

All rows of the Treeview is first removed. Then list is crated by using DataFrame df and the same is inserted to the Treeview.
def my_upd(): # add rows to Treeview
    global df , trv
    i=1
    for item in trv.get_children(): # remove all rows 
        trv.delete(item)
    r_set=df.to_numpy().tolist() # Create list of list using rows 
    #print(r_set)
    for dt in r_set:  
        v=[r for r in dt] # creating a list from each row 
        trv.insert("",'end',iid=i,values=v) # adding row
        i=i+1

my_sort() : Sorting the DataFrame columns

This function receives the column name and sort the DataFrame using same. After sorting using the DataFrame sort_values(), my_upd() is called to refresh the rows of the Treeview with the new sorted order.
def my_sort(col): # Update the dataframe after sorting
    global df,order 
    if order:
        order=False # set ascending value
    else:
        order=True
    df=df.sort_values(by=[col],ascending=order)
    my_upd() # refresh the Treeview 
from tkinter import ttk
import tkinter as tk
from tkinter import filedialog
import os
from datetime import datetime
import pandas as pd
# Creating tkinter my_w
my_w = tk.Tk()
my_w.geometry("550x380") 
my_w.title("www.plus2net.com")  
order=True
b1=tk.Button(my_w,text='Select directory',font=22,
    command=lambda:my_select(),bg='lightgreen')
b1.grid(row=1,column=1,padx=10,pady=10)

lb1=tk.Label(my_w,text='',bg='yellow',font=18)
lb1.grid(row=1,column=2,padx=2,columnspan=2)
# Using treeview widget
df = pd.DataFrame() # empty DataFrame object

def my_select():  # Select directory 
    my_dir = filedialog.askdirectory() # dialog box to select directory 
    lb1.config(text=my_dir) # update the text of Label with directory path
    my_treeview(my_dir) # call function with path 
def my_treeview(path):
    global trv
    trv = ttk.Treeview(my_w, selectmode ='browse',show='headings')
    trv.grid(row=2,column=1,columnspan=3,padx=30,pady=10)
    # column identifiers 
    trv["columns"] = ("1", "2","3","4")
    trv.column("1", width = 150, anchor ='w')
    trv.column("2", width = 100, anchor ='c')
    trv.column("3", width = 100, anchor ='c')
    trv.column("4", width = 70, anchor ='c')

    trv.heading(1, text ="Name",anchor='w',command=lambda :my_sort('Name'))
    trv.heading(2, text ="Type",anchor='c',command=lambda :my_sort('Type'))
    trv.heading(3, text ="Date Modified",anchor='c',command=lambda :my_sort('Date'))
    trv.heading(4, text ="Size",anchor='c',command=lambda :my_sort('Size'))
        
    my_details(path) # Pass the path to create dataframe
def my_details(path): # Create the DataFrame with file details 
    global df
    l1=['Name','Type','Date','Size'] # column names 
    df = pd.DataFrame(columns=l1) # add columns to DataFrame
    files=os.listdir(path)
    for f in files:
        f_path=path+'\\'+f # Path with file name
        t_stamp=os.path.getmtime(f_path) # for file modificaton time
        #t_stamp=os.path.getctime(path) # for file Creation time
        f_name,f_extension=os.path.splitext(f_path) # get file extension
        size=os.path.getsize(f_path) # size of file in bytes 
        dt_mod = datetime.fromtimestamp(t_stamp) # date object 
        #print('File Modified on:', dt_mod)  # Prting date and time 
        m_date = datetime.strftime(dt_mod, '%Y-%m-%d') # Change format 
        #print(f, f_extension, m_date,size)
        my_list=[f,f_extension,m_date,size] # List with file data
        df.loc[len(df)]=my_list # adding list to DataFrame
    my_upd() 
def my_upd(): # add rows to Treeview
    global df , trv
    i=1
    for item in trv.get_children(): # remove all rows 
        trv.delete(item)
    r_set=df.to_numpy().tolist() # Create list of list using rows 
    #print(r_set)
    for dt in r_set:  
        v=[r for r in dt] # creating a list from each row 
        trv.insert("",'end',iid=i,values=v) # adding row
        i=i+1
def my_sort(col): # Update the dataframe after sorting
    global df,order 
    if order:
        order=False # set ascending value
    else:
        order=True
    df=df.sort_values(by=[col],ascending=order)
    my_upd() # refresh the Treeview 
my_w.mainloop()
Part I : Searching DataFrame and displaying result in Treeview
Part III : Selection Columns of DataFrame using CheckButtons
Projects in Tkinter
Create Pandas DataFrame by reading Google Analytics csv file from Tkinter GUI Search DataFrame by user inputs through Tkinter.
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer