There is an interface I developed with Tkinter. This interface has a start, a stop, and a few text frames. There are sequential test commands that run a specific procedure (function) with the start button. It prints the output of the test commands in a text frame line by line (there are also some wait/sleep states in the function).
The problem is that when the user clicks the stop button, these test steps execute all the steps without a timeout period and the output is "TEST COMPLETE". However, when the user clicks the stop button, the test step should be broken from where it was last left and the output should be "TEST INCOMPLETE - PROGRAM STOPED".
To share the code structure briefly:
def PROCEDURE_STAGE(self):
self.must_stop = threading.Event()
while not self.must_stop.is_set():
self.process_text_base.insert("end", "PROGRAM STARTING..." + "\n")
...
...
...
self.must_stop.wait(timeout=2)
...
...
...
self.process_text_base.insert("end", "\n" + " TEST COMPLETE " + "\n")
self.process_text_endline()
self.must_stop.wait(timeout=5)
return
self.process_text_base.insert("end", " TEST INCOMPLETE - PROGRAM STOPED ")
self.process_text_endline()
def START_TEST_PROCEDURE(self):
self.t1 = threading.Thread(target=self.PROCEDURE_STAGE)
self.t1.start()
def STOP_TEST_PROCEDURE(self):
self.must_stop.set()
What I want to do is; the user should be able to stop this function in any situation with the "Stop" button from the outside and the loop should be broken wherever it is.
I used a flag as one of the possible solutions, but I realized that this also needs to be checked periodically in the function. It is not a method I want in terms of performance, quality, and code repetition. It is also not convenient in terms of security as it will stop after a few seconds of delay in standby/sleep states.
As a different solution, I tried creating a threading.Event() object and assigning it to the class property must_stop to terminate the loop, but I couldn't get exactly the result I wanted. It executes all the commands in the while loop one by one and then exits. Also, when using the must_stop property here, I expected it to print "TEST INCOMPLETE - PROGRAM STOPED" in the text frame, but the last command it prints is "TEST COMPLETE".
When this is done, the tkinter interface does not freeze at all. I don't want it to freeze anyway.