The aim is to have the user input a directory and a word in a tkinter GUI. The program searches for this word in the directory/subdirectories. If the word is found the path of the file should be printed. The number of directories and files searched should also be printed + the occurences of the word. The code below might have several issues, but gives me UnboundLocalError: local variable 'folders' referenced before assignment - any ideas?
import os
import tkinter as tk
results = []
folders = 0
files = 0
words = 0
def recSearch(path,word):
foldername = os.listdir(path)
for i in foldername:
if os.path.isdir(f"{path}\\{i}"):
results.append(f"{path}\\{i}")
folders += 1
recSearch((f"{path}\\{i}"),word)
else:
with open(os.path.join(path, i), "r") as fileObject:
for j in fileObject:
if word in j:
files += 1
words += j.count(word)
def click():
recSearch(path.get(), word.get())
text.insert('end', "Search start.\n ------------------\n")
for i in results:
text.insert('end', i + "\n")
text.insert('end', '------------------\n')
text.insert('end', f"Searched {folders} directories and found {files} files with {words} occurences of {word.get()}")
window = tk.Tk()
window.title("Find word")
path = tk.StringVar()
entry = tk.Entry(window, textvariable=path, width=50)
entry.insert(-1,"Directory or filename")
word = tk.StringVar()
word_entry = tk.Entry(window, textvariable=word, width=20)
word_entry.insert(-1, "Word")
search_button = tk.Button(window, text="Search", width=15, command=click)
text = tk.Text(window, height=50, width=180)
entry.grid(row=0, column=0)
word_entry.grid(row=0, column=1)
search_button.grid(row=0, column=2)
text.grid(row=1, columnspan=3)
window.mainloop()