How to stop tkinter after function?

I have a problem stopping the feed; the cancel argument has no effect on the after method. Although "feed stopped" is displayed on the console.

I am trying to create one button that starts the feed, and another that stops the feed.

from Tkinter import Tk, Button import random def goodbye_world(): print "Stopping Feed" button.configure(text = "Start Feed", command=hello_world) print_sleep(True) def hello_world(): print "Starting Feed" button.configure(text = "Stop Feed", command=goodbye_world) print_sleep() def print_sleep(cancel=False): if cancel==False: foo = random.randint(4000,7500) print "Sleeping", foo root.after(foo,print_sleep) else: print "Feed Stopped" root = Tk() button = Button(root, text="Start Feed", command=hello_world) button.pack() root.mainloop() 

With an exit:

 Starting Feed Sleeping 4195 Sleeping 4634 Sleeping 6591 Sleeping 7074 Stopping Feed Sleeping 4908 Feed Stopped Sleeping 6892 Sleeping 5605 
+6
source share
2 answers

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.

+13
source

When you call root.after(...) , it returns an identifier. You must keep track of this identifier (for example, store it in an instance variable), and then you can call root.after_cancel(after_id) later to cancel it.

+14
source

Source: https://habr.com/ru/post/911142/


All Articles