here is my python app. i am able to open the search result file. but after opening the file and going back to the app the app doesnt respond. but after closing the file it responds. heres my code.
please fix that issue
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import chardet
import configparser
import threading
import re
import sys
import time
import subprocess
search_started = True
search_terminated.set(False)
files_str = directory_entry.get()
keywords = keywords_entry.get()
if not files_str or not keywords:
error_message = ""
if not files_str:
error_message = "You have not selected any journals."
if not keywords:
if error_message:
error_message += "\n"
error_message += "You have not added any keywords."
messagebox.showerror("Error", error_message)
return
config = configparser.ConfigParser()
config.read("keywords.ini")
if "Keywords" not in config.sections():
config.add_section("Keywords")
config.set("Keywords", "search_keywords", keywords)
with open("keywords.ini", "w") as configfile:
config.write(configfile)
files = files_str.split("||")
if not files or not keywords:
message = "Please select files and enter keywords to search.\n\n"
messagebox.showerror("Error", message)
return
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
paused_search_var.set(False)
search_started = True
file_path = None
def search():
nonlocal file_path
for file_path in files:
if search_terminated.get():
break
while paused_search_var.get():
time.sleep(0.1)
if os.path.isfile(file_path):
content = None
with open(file_path, "rb") as f:
raw_data = f.read()
detected_encoding = chardet.detect(raw_data)["encoding"]
try:
with open(file_path, "r", encoding=detected_encoding) as f:
content = f.read()
except UnicodeDecodeError:
with open(file_path, "r", encoding="ISO-8859-1") as f:
content = f.read()
content_lower = content.lower()
for keyword in keywords.split(","):
keyword = keyword.strip()
keyword_lower = keyword.lower()
start = content_lower.find(keyword_lower)
while start != -1:
end = start + len(keyword)
result = f"{file_path}: {keyword}: {start}-{end}"
results_listbox.insert(tk.END, result)
start = content_lower.find(keyword_lower, end)
if search_terminated.get():
break
search_thread = threading.Thread(target=search)
search_thread.start()
while search_thread.is_alive():
app.update()
time.sleep(0.1)
if search_terminated.get():
break
if not results_listbox.get(0, tk.END):
messagebox.showinfo("Message", "No results were found.")
else:
messagebox.showinfo("Message", "Search completed.")
pause_button.config(text="Pause")
paused_search_var.set(False)
if instance_data:
display_instance(-1, file_path)
search_started = False
def pause_search():
global search_started, paused_search_var
code
if not search_started:
messagebox.showerror("Error", "Search process has not begun.")
return
if paused_search_var.get():
pause_button.config(text="Pause")
paused_search_var.set(False)
else:
if not results_listbox.get(0, tk.END):
return
pause_button.config(text="Resume")
paused_search_var.set(True)
def reset():
global search_started
code
if search_started:
if not paused_search_var.get():
messagebox.showerror(
"Error", "Please pause the current search before resetting."
)
else:
search_terminated.set(True)
search_started = False
directory_entry.delete(0, tk.END)
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
instance_data.clear()
search_started = False
search_terminated.set(False)
else:
directory_entry.delete(0, tk.END)
results_listbox.delete(0, tk.END)
content_text.delete(1.0, tk.END)
instance_data.clear()
search_started = False
def close_app():
global search_started
code
if search_started:
search_terminated.set(True)
if messagebox.askyesno("Exit", "Do you want to close the application?"):
app.destroy()
def show_about():
messagebox.showinfo("About", "Coded by U2816.")
instruction_label = tk.Label(
app, text="(Single-click to view content, Double-click to open file)"
)
instruction_label.place(x=163, y=220)
config = configparser.ConfigParser()
config.read("keywords.ini")
if "Keywords" in config.sections() and "search_keywords" in config.options("Keywords"):
keywords_entry.insert(0, config.get("Keywords", "search_keywords"))
app.mainloop()
The issue seems to be with the search() function in your code. This function takes a long time to execute and blocks the main thread. This is why the app becomes unresponsive and does not respond when you try to interact with it.
To fix this issue, you can run the search() function in a separate thread so that it does not block the main thread. You can also use the after() method to periodically update the UI and check if the search has been terminated.
Here's the updated code for the search() function:
code
def search():
nonlocal file_path
for file_path in files:
if search_terminated.get():
break
while paused_search_var.get():
time.sleep(0.1)
if os.path.isfile(file_path):
content = None
with open(file_path, "rb") as f:
raw_data = f.read()
detected_encoding = chardet.detect(raw_data)["encoding"]
try:
with open(file_path, "r", encoding=detected_encoding) as f:
content = f.read()
except UnicodeDecodeError:
with open(file_path, "r", encoding="ISO-8859-1") as f:
content = f.read()
content_lower = content.lower()
for keyword in keywords.split(","):
keyword = keyword.strip()
keyword_lower = keyword.lower()
start = content_lower.find(keyword_lower)
while start != -1:
end = start + len(keyword)
result = f"{file_path}: {keyword}: {start}-{end}"
results_listbox.insert(tk.END, result)
start = content_lower.find(keyword_lower, end)
if search_terminated.get():
break
app.after(100, check_search_termination)
def check_search_termination():
app.update()
if search_terminated.get():
return
if len(threading.enumerate()) <= 1:
if not results_listbox.get(0, tk.END):
messagebox.showinfo("Message", "No results were found.")
else:
messagebox.showinfo("Message", "Search completed.")
pause_button.config(text="Pause")
paused_search_var.set(False)
if instance_data:
display_instance(-1, file_path)
search_started = False
else:
app.after(100, check_search_termination)
In the new search() function, we're calling the check_search_termination() function periodically using the after() method. This checks if the search has been terminated, and if not, it checks if the search is still running. If the search has completed, it displays a message box and updates the UI accordingly. If the search is still running, it calls itself again after 100 milliseconds.
I hope this helps! Let me know if you have any other questions.