How to stop Tkinter after function?

TkinterServer Side ProgrammingProgramming

Tkinter functions can be created with the help of threading concept where we define, when a function should run or stop. A Tkinter function can be scheduled using the after(time, callback) function.

Let us suppose that we have created a callback function that forces the main window to be closed after some time. There might be times when we need to stop the scheduling of the function. In order to cancel or stop a particular schedule of a callback function, we can use after_cancel(widget) function.

Example

In the given example, the script will close the main window after 3 seconds but after initializing after_cancel (parent), it will stop the after function to be executed.

#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Initialize a Label widget
Label(win, text= "This window will get closed after 3 seconds...",
font=('Helvetica 20 bold')).pack(pady=20)
#Automatically close the window after 3 seconds
win.after_cancel(win)
win.after(3000,lambda:win.destroy())
win.mainloop()

Output

Running the above code will display a window that will show some message on the screen.

If we will remove the line win.after_cancel(win), the window will close automatically after 3 seconds.

raja
Published on 03-May-2021 09:16:43
Advertisements