The problem is that even if you call print_sleep
with True
to stop the loop, you are already waiting for work. Pressing the stop button will not trigger a new task, but the old task still exists, and when it calls itself, it goes to False, which causes the loop to continue.
You need to cancel the pending task so that it does not start. For instance:
def cancel(): if self._job is not None: root.after_cancel(self._job) self._job = None def goodbye_world(): print "Stopping Feed" cancel() button.configure(text = "Start Feed", command=hello_world) def hello_world(): print "Starting Feed" button.configure(text = "Stop Feed", command=goodbye_world) print_sleep() def print_sleep(): foo = random.randint(4000,7500) print "Sleeping", foo self._job = root.after(foo,print_sleep)
Note. Make sure you initialize self._job
somewhere, for example, in the constructor of your application object.
source share