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.

b1 : Button, On click of this the function my_select is called.
lb1 : Label to show the user selected path
trv : Treeview to display file details in rows.

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 called on click of the Button b1. This will open the directory selection Filedialog dialog box and on selection of the directory path by user, the same is displayed on the Label lb1 by using config() method.
def my_select():
    my_dir = filedialog.askdirectory() # select directory
    if my_dir: # user has not cancelled the dialog box
        l1.config(text=my_dir) # update Label with directory path
        my_treeview() # Create the Treeview structure
        my_details(my_dir) # Collect file details of selected 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() to sort the Pandas DataFrame using the column.
def my_treeview():
    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 Modified'))
    trv.heading(4, text ="Size",anchor='c',command=lambda :my_sort('Size'))

my_details

This function receives the path and collect all details of the files and directories inside the path.
All details are added to Pandas DataFrame df.
def my_details(path):
    global trv,df
    #path = "E:\\testing\\images\\test3.png"  # Directory Path
    df.drop(df.index,inplace=True) # remove all rows of the DataFrame
    files=os.listdir(path) # List of files and dirs. of the path
    for f in files: # Looping through all files and dirs
        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)
        df_new=[f,f_extension,m_date,size] # List with all details
        df.loc[len(df)]=df_new # add list as new row to DataFrame
    my_upd() # Call to show Treeview using the DataFrame

my_upd()

Here we add the data to Treeview trv.

First we delete all previous data if any in the Treeview. Then we insert rows by taking the same from the Pandas DataFrame df.

Each time this function is called it will update the data of the Treeview by using the fresh data from the Pandas DataFrame df.
One Vertical Scrollbar is added for easy navigation.
def my_upd():
    global trv,df
    trv.delete(*trv.get_children())# delete all rows from treeview
    r_set = df.to_numpy().tolist()  # Create list of list using rows
    for dt in r_set:
        trv.insert("", "end",  values=dt)  # adding row to TreeView  

    # Adding vertical scrollbar
    vsb = ttk.Scrollbar(my_w, orient="vertical", command=trv.yview)
    vsb.grid(row=2, column=4, sticky="ns")
    trv.configure(yscrollcommand=vsb.set) 

my_sort()

This function will receive the column name and toggle the Boolean value of the variable order. Based on the value of order the option ascending is set to True or False.

The method sort_values() is used to update the Pandas DataFrame df with new sorting order based on the input column name.

By calling the my_upd() the Treeview is refreshed to reflect the changes as per the new sorting order.
def my_sort(col_name): # Update the dataframe after sorting
    global df,order
    if order:
        order=False # set ascending value
    else:
        order=True
    df=df.sort_values(by=[col_name],ascending=order) # sort values
    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") # width x height of the window
my_w.title("www.plus2net.com")  

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)

l1=tk.Label(my_w,text='',bg='yellow',font=18)
l1.grid(row=1,column=2,padx=2,columnspan=2)

df = pd.DataFrame(columns=['Name','Type','Date Modified','Size']) # blank DataFrame
order=True
def my_select():
    my_dir = filedialog.askdirectory() # select directory
    if my_dir: # user has not cancelled the dialog box
        l1.config(text=my_dir) # update Label with directory path
        my_treeview() # Create the Treeview structure
        my_details(my_dir) # Collect file details of selected path
# Using treeview widget
def my_treeview():
    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 Modified'))
    trv.heading(4, text ="Size",anchor='c',command=lambda :my_sort('Size'))

def my_details(path):
    global trv,df
    #path = "E:\\testing\\images\\test3.png"  # Directory Path
    df.drop(df.index,inplace=True) # remove all rows of the DataFrame
    files=os.listdir(path) # List of files and dirs. of the path
    for f in files: # Looping through all files and dirs
        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)
        df_new=[f,f_extension,m_date,size] # List with all details
        df.loc[len(df)]=df_new # add list as new row to DataFrame
    my_upd() # Call to show Treeview using the DataFrame
def my_upd():
    global trv,df
    trv.delete(*trv.get_children())# delete all rows from treeview
    r_set = df.to_numpy().tolist()  # Create list of list using rows
    for dt in r_set:
        trv.insert("", "end",  values=dt)  # adding row to TreeView  

    # Adding vertical scrollbar
    vsb = ttk.Scrollbar(my_w, orient="vertical", command=trv.yview)
    vsb.grid(row=2, column=4, sticky="ns")
    trv.configure(yscrollcommand=vsb.set)
def my_sort(col_name): # Update the dataframe after sorting
    global df,order
    if order:
        order=False # set ascending value
    else:
        order=True
    df=df.sort_values(by=[col_name],ascending=order) # sort values
    my_upd() # refresh the Treeview
my_w.mainloop()
Part I : Searching DataFrame and displaying result in Treeview Part II : Selection of row in Treeview Part III : Selection Columns of DataFrame using CheckButtons
Adding row to Treeview after inserting to MySQL table
Treeview Records of MySQL Pagination of Records of MySQL Delete Records Treeview Columns sorting using Pandas DatraFrame
Browsing directory and displaying file details with sorting using Treeview 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-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer