Python | after method in Tkinter

Tkinter provides a variety of built-in functions develop interactive and featured GUI (Graphical User Interface). after() function is also a Universal function which can be used directly on the root as well as with other widgets.

after(parent, ms, function = None, *args)

Parameters:
parent: is the object of the widget or main window whichever is using this function.
ms: is the time in miliseconds.
function: which shall be called.
*args: other options.

Code #1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
  
# time function used to calculate time
from time import time
  
# creating tkinter window
root = Tk()
  
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
print('Running...')
# Calculating starting time
start = time()
  
# in after method 5000 miliseconds
# is passed i.e after 5 seconds
# main window i.e root window will
# get destroyed
root.after(5000, root.destroy)
  
mainloop()
  
# calculating end time
end = time()
print('Destroyed after % d seconds' % (end-start))

chevron_right


Output:


When you run the program it will show a Tkinter window having a Button but after 5 seconds the window gets destroyed.

Code #2: Prompting a message after certain time (in our program after 5 seconds).

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
from tkinter.messagebox import _show
  
# creating tkinter window
root = Tk()
root.geometry('200x100 + 300 + 250')
  
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
  
# in after method 5000 miliseconds
# is passed i.e after 5 seconds
# a message will be prompted
root.after(5000, lambda : _show('Title', 'Prompting after 5 seconds'))
  
# Destroying root window after 6.7 seconds
root.after(6700, root.destroy)
  
mainloop()

chevron_right


Output:
In below output a messagebox will prompt after 5 seconds you can even call any function after a certain period of time by passing the function name.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.