How to temporarily remove a Tkinter widget without using just .place?


To place Tkinter widgets inside a Frame or a Canvas, you can use various geometry managers. The geometry manager allows you to set the layout of the widget and how they will appear in the tkinter window. The place() method is one of the simplest geometry managers which is used to set the position of a widget relatively and explicitly to the window. We can also use the place() method to separate the widgets from each other, as it supports the relative property to position the widget with respect to others.

In some cases, if you want to temporarily remove a particular widget from an application, you can use the place_forget() method. You may also use pack_forget() and grid_forget() methods for various geometry managers to temporarily remove a widget from an application. We can take an example to understand its practical use-case.

Example

# Import the library
from tkinter import *

# Create an instance of window
win=Tk()

# Set the geometry of the window
win.geometry("700x300")

def forget_label():
   label.place_forget()

# Create a label widget
label=Label(win, text="This is a new Label text", font='Arial 17 bold')
label.place(relx=0.5, rely=0.2, anchor=CENTER)

# Create a button
button=Button(win, text="Remove It", command=forget_label)
button.place(relx=0.5, rely=0.5, anchor=CENTER)

win.mainloop()

Output

Running the above code will display a window with a Label widget and a Button.

Whenever the button "Remove It" is pressed, it will remove the label widget from the window.

Updated on: 22-Dec-2021

745 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements