How to Cancel Scheduled Functions with after_cancel() in Python Tkinter?

In this tutorial, I will explain how to cancel scheduled functions with after_cancel() in Python Tkinter library. As a developer working on various projects across the USA, I came across a situation where I needed to cancel a scheduled function in Python Tkinter. Then I explored more about this topic and I will share my findings in this article with suitable examples.

The after() Method

Before getting into after_cancel() , let’s briefly discuss the after() method. The after() method is used to schedule a function to be called after a specified number of milliseconds. Here’s an example:

import tkinter as tk

def greet():
    print("Hello, John!")

root = tk.Tk()
root.after(3000, greet)  # Schedule greet() to run after 3000 milliseconds (3 seconds)
root.mainloop()

You can see the output in the screenshot below.

Cancel a Scheduled Functions with after_cancel() in Python Tkinter

In this example, the greet() function will be called after a delay of 3 seconds.

Read Python Tkinter On-Off Switch

Cancel Scheduled Functions with after_cancel() in Python Tkinter

Now, let’s say you have scheduled a function using after() , but you want to cancel it before it gets executed. This is where the after_cancel() method comes into play. The after_cancel() method takes the identifier returned by the after() method and cancels the scheduled function.

Here’s an example that demonstrates the usage of after_cancel():

import tkinter as tk

def start_timer():
    global timer_id
    timer_id = root.after(5000, show_message)
    start_button.config(state=tk.DISABLED)
    cancel_button.config(state=tk.NORMAL)

def cancel_timer():
    root.after_cancel(timer_id)
    start_button.config(state=tk.NORMAL)
    cancel_button.config(state=tk.DISABLED)

def show_message():
    print("Time's up, Emily!")

root = tk.Tk()
root.title("Timer Example")

start_button = tk.Button(root, text="Start Timer", command=start_timer)
start_button.pack()

cancel_button = tk.Button(root, text="Cancel Timer", command=cancel_timer, state=tk.DISABLED)
cancel_button.pack()

root.mainloop()

In this example:

  1. The start_timer() function is called when the “Start Timer” button is clicked. It schedules the show_message() function to run after 5 seconds using root.after(5000, show_message). The returned identifier is stored in the timer_id variable. The “Start Timer” button is disabled, and the “Cancel Timer” button is enabled.
  2. If the “Cancel Timer” button is clicked before the 5 seconds elapse, the cancel_timer() function is called. It is used root.after_cancel(timer_id) to cancel the scheduled show_message() function. The “Start Timer” button is re-enabled, and the “Cancel Timer” button is disabled.
  3. If the 5 seconds pass without cancellation, the show_message() function is executed, printing “Time’s up, Emily!” to the console.

You can see the output in the screenshot below.

How to Cancel a Scheduled Functions with after_cancel() in Python Tkinter

Check out Python Tkinter notebook Widget

Example

Let’s consider a real-world scenario where after_cancel() can be useful. Suppose you’re building a quiz application using Tkinter. You want to give the user a limited time to answer each question. If the user answers the question within the time limit, you want to cancel the timer and move on to the next question. Here’s an example:

import tkinter as tk

class QuizApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Quiz App")

        self.question_label = tk.Label(root, text="What is the capital of California?")
        self.question_label.pack()

        self.answer_entry = tk.Entry(root)
        self.answer_entry.pack()

        self.submit_button = tk.Button(root, text="Submit", command=self.check_answer)
        self.submit_button.pack()

        self.result_label = tk.Label(root, text="")
        self.result_label.pack()

        self.timer_id = None
        self.start_timer()

    def start_timer(self):
        self.timer_id = self.root.after(10000, self.time_up)

    def check_answer(self):
        user_answer = self.answer_entry.get()
        if user_answer.lower() == "sacramento":
            self.root.after_cancel(self.timer_id)
            self.result_label.config(text="Correct!")
        else:
            self.result_label.config(text="Wrong answer. Try again.")

    def time_up(self):
        self.result_label.config(text="Time's up! The correct answer was Sacramento.")
        self.submit_button.config(state=tk.DISABLED)

root = tk.Tk()
quiz_app = QuizApp(root)
root.mainloop()

In this quiz application:

  1. The start_timer() method is called when the QuizApp is initialized. It schedules the time_up() method to run after 10 seconds using self.root.after(10000, self.time_up). The returned identifier is stored in the self.timer_id variable.
  2. If the user submits the correct answer within the 10-second time limit, the check_answer() method is called. It cancels the scheduled time_up() method self.root.after_cancel(self.timer_id) and displays “Correct!” in the result label.
  3. If the user submits a wrong answer, the check_answer() method displays “Wrong answer. Try again.” in the result label, and the timer continues.
  4. If the 10 seconds elapse without the user submitting the correct answer, the time_up() method is called. It displays “Time’s up! The correct answer was Sacramento.” in the result label and disables the submit button.

You can see the output in the screenshot below.

Cancel a Scheduled Functions with after_cancel() in Python Tkinter quiz app

Read Python Tkinter Events

Conclusion

In this tutorial, I have explained to you how to cancel scheduled functions with after_cancel() in Python Tkinter library. I discussed how to use the after() method and how to cancel the scheduled function with after_center(). I also discussed a real-world example.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.