A GUI to look for files in your hard drive with tkinter

Today we are going to use tkinter and os.walk to open files that we’ve been looking for on the hard drive. Let’s take a look at some very basic code. Next time we will make some widgets to search the files from the GUI, not using the code inside the script.

import os
from operator import itemgetter
import tkinter as tk

def listOfFiles(wit, folder):
    """args: 1) word to search
    2) folder to start search"""
    outputfile = wit + "_found.txt"
    with open(outputfile, "w", encoding="utf-8") as txt_file_with_list:
        fn_list = ""
        rfn_list = []
        for r, d, f in os.walk(folder):
            fn_list += f"\n---------------------------------\n{r}\n\n"
            for file in f:
                if wit in file:
                    fn_list += f"\t{r}\\{file}\n"
                    rfn_list.append([r,file])
    
        txt_file_with_list.write(fn_list)
    os.startfile(outputfile)
    return rfn_list

def curselect(evt):
    value=str((lb.get(lb.curselection())))
    os.startfile(value)

# ---------------------- G.U.I. --------------------------
root = tk.Tk()
root.title("SearchFile")
root.geometry("400x400+400+400")
scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
lb = tk.Listbox(root, yscrollcommand=scrollbar.set)
scrollbar.config(command=lb.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
lb.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
lb.bind('<<ListboxSelect>>', curselect)
fn_list = sorted(listOfFiles(".py","H:\\pylearning\\"), key=itemgetter(1), reverse=True)



for f in fn_list:
    lb.insert(0,f[0]+"\\"+f[1])

root.mainloop()
# you can put the extension or any word in title
#searchfiles('.py', 'H:\\pylearning\\')

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.