after method in Python Tkinter

Tkinter is a python library to make GUIs. It has many built in methods to create and manipulate GUI windows and other widgets to show the data and GUI events. In this article we will see how the after method is used in a Tkinter GUI.


.after(delay, FuncName=FuncName)
This method calls the function FuncName after the given delay in milisecond

Displaying Widget

Here we make a frame to display a list of words randomly. We use the random library along with the after method to call a function displaying a given list of text in a random manner.


import random
from tkinter import *

base = Tk()

a = Label(base, text="After() Demo")

contrive = Frame(base, width=450, height=500)

words = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat','Sun']
#Display words randomly one after the other.
def display_weekday():
   if not words:
   rand = random.choice(words)
   character_frame = Label(contrive, text=rand)

base.after(0, display_weekday)

Running the above code gives us the following result:

On running the same program again we get the result showing different sequence of the words.

Stopping Processing

In the next example we will see how we can use the after method as a delay mechanism to wait for a process to run for a certain amount of time and then stop the process. We also use the destroy method to stop the processing.


from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button

from time import time

base = Tk()

stud = Button(base, text = 'After Demo()')
stud.pack(side = TOP, pady = 8)

print('processing Begins...')

begin = time()

base.after(3000, base.destroy)


conclusion = time()
print('process destroyed in % d seconds' % ( conclusion-begin))

Running the above code gives us the following result:

processing Begins...
process destroyed in 3 seconds