How it works...

To unschedule a callback, we will first need the alarm identifier returned by after(). We will store this identifier in the scheduled_id attribute, since we will need it in a separate method:

    def start_action(self):
self.button.config(state=tk.DISABLED)
self.cancel.config(state=tk.NORMAL)
self.scheduled_id = self.after(5000, self.init_buttons)

Then, this field is passed to after_cancel() in the callback of the Stop button:

    def cancel_action(self):
print("Canceling scheduled", self.scheduled_id)
self.after_cancel(self.scheduled_id)
self.init_buttons()

In our case, it is important to disable the Start button once it is clicked, because if start_action() is called twice, scheduled_id would be overridden, and the Stop button could only cancel the last scheduled action.

As a side note, after_cancel() has no effect if we call it with an alarm identifier that has already been executed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset