I am creating a GUI with tkinter and I need help. I have two buttons, one for starting my code and another one for exit the GUI and stop the code running. Here is part of my code:
def close_app():
window.destroy()
def run_app():
.... do something...
window = tk.Tk() #start of the app
button_run = tk.Button(frame_bottom, text = "Search", command = run_app)
button_run.grid(column=0, row=0, sticky='w', padx=100, pady=2)
button_close = tk.Button(frame_bottom, text = "Exit", command = close_app)
button_close.grid(column=1, row=0, sticky='e', padx=100, pady=2)
window.mainloop() #end of the app
The problem is that when I press "Exit" button the GUI does not respond anymore and the code still continues in the background. How can I stop the execution of the program with my Exit button? I tried also to delete the Exit button and to stop the code simply closing the GUI, but the problem is the same, after a while "not respondind" appears. How can I solve it?
CodePudding user response:
Replace frame_bottom
with window
CodePudding user response:
From the code you posted it's hard to tell, but if run_app
is doing something that takes very long the function won't be stopped - that's why your GUI is freezing.
If run_app
contains a loop, setting a global variable in close_app
then checking inside the loop if that variable is set and if it is stopping the loop would be the solution:
import time
import tkinter as tk
exit_app = False
def close_app():
exit_app = True
window.destroy()
def run_app():
for i in range(100):
if exit_app:
break
time.sleep(1)
window = tk.Tk()
button_run = tk.Button(frame_bottom, text = "Search", command = run_app)
button_run.grid(column=0, row=0, sticky='w', padx=100, pady=2)
button_close = tk.Button(frame_bottom, text = "Exit", command = close_app)
button_close.grid(column=1, row=0, sticky='e', padx=100, pady=2)
window.mainloop()
(Not tested as your code does not define frame_bottom
)
If it doesn't run in a loop, the last solution would be to call sys.exit
in close_app
which should exit yur script immediately.