If we want to unmap any widget from the screen or toplevel then forget()
method is used. There are two types of forget method forget_pack()
( similar to forget()
) and forget_grid()
which are used with pack()
and grid()
method respectively.
forget_pack()
method –
Syntax: widget.forget_pack()
widget can be any valid widget which is visible.
Code #1:
from tkinter import *
from tkinter.ttk import *
root = Tk()
def forget(widget):
widget.forget()
def retrieve(widget):
widget.pack(fill = BOTH, expand = True )
b1 = Button(root, text = "Btn 1" )
b1.pack(fill = BOTH, expand = True )
b2 = Button(root, text = "Btn 2" , command = lambda : forget(b1))
b2.pack(fill = BOTH, expand = True )
b3 = Button(root, text = "Btn 3" , command = lambda : retrieve(b1))
b3.pack(fill = BOTH, expand = True )
mainloop()
|
Output:

After forget

After retrieval

Notice the difference in the position of Button 1 before and after forget as well as after retrieval.
forget_grid()
method –
Syntax: widget.forget_grid()
widget can be any valid widget which is visible.
Note : This method can be used only with grid()
geometry methods.
Code #2:
from tkinter import *
from tkinter.ttk import *
root = Tk()
def forget(widget):
widget.grid_forget()
def retrieve(widget):
widget.grid(row = 0 , column = 0 , ipady = 10 , pady = 10 , padx = 5 )
b1 = Button(root, text = "Btn 1" )
b1.grid(row = 0 , column = 0 , ipady = 10 , pady = 10 , padx = 5 )
b2 = Button(root, text = "Btn 2" , command = lambda : forget(b1))
b2.grid(row = 0 , column = 1 , ipady = 10 , pady = 10 , padx = 5 )
b3 = Button(root, text = "Btn 3" , command = lambda : retrieve(b1))
b3.grid(row = 0 , column = 2 , ipady = 10 , pady = 10 , padx = 5 )
mainloop()
|
Output:

After Forget

After Retrieval

Notice that the position of Button 1 remains same after forget and retrieval. With grid_forget()
method, you can place it at any grid after retrieval but generally, the original grid is chosen.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Nov, 2021
Like Article
Save Article