How do I stop tkinter after function?

The problem is that, even though you’re calling print_sleep with True to stop the cycle, there’s already a pending job waiting to fire. Pressing the stop button won’t cause a new job to fire but the old job is still there, and when it calls itself, it passes in False which causes the loop to continue.

You need to cancel the pending job so that it doesn’t run. For example:

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, such as in the constructor of your application object.

Leave a Comment