Here's how it could be done by making the file searching function run in a separate thread, as I suggested in a comment. It uses a Threading.Event
to communicate between the main thread which is running the tkiner GUI, and the thread doing the searching. I also fixed the search function so it properly creates the file when it wasn't found at end.
import os
import sys
import tkinter as tk
from threading import Event, Thread
EVENT_TIMEOUT = .01 # A very short timeout - seconds.
POLLING_DELAY = 1000 # How often to check search status - millisecs.
def file_search(event):
search_folder = r"C:\Users"
target = "Details.txt"
found = False
for root, dirs, files in os.walk(search_folder):
for filename in files:
if filename.endswith(target): # "if filename == target" would work fine here.
fileLocation = os.path.join(root, filename)
print(fileLocation, "file found")
found = True
break
if found:
break # Quit looking.
if not found:
createFile = open(target, "w") # Creates empty file in cwd.
createFile.close()
fileLocation = os.path.join(os.getcwd(), target)
print(fileLocation, "file created")
event.set() # Signal search has completed.
def check_status(parent, event):
event_is_set = event.wait(EVENT_TIMEOUT)
if event_is_set: # Done searching?
parent.destroy()
sys.exit()
else: # Continue polling.
parent.after(POLLING_DELAY, check_status, parent, event)
parent = tk.Tk()
text = tk.Label(parent, text="Loading...")
text.pack()
event = Event()
thread = Thread(target=file_search, args=(event,))
check_status(parent, event) # Starts the polling of search status.
thread.start()
parent.mainloop()