How to Hide, Recover and Delete Tkinter Widgets?
Tkinter is a Python Package for creating GUI(Graphical User Interface) applications. Tkinter provides us with a variety of common GUI elements which we can use to build out interfaces — such as buttons, label, frame, message, menu, and various kind of entry fields and display areas. We call these elements of Widgets.
Widget is an element of Graphical User Interface (GUI) that illustrates information so that a user can interact with the OS. In Tkinter, Widgets are objects; instances of classes that represent buttons, frames, and so on.
In this article, we will demonstrate how to Hide, Recover, and Delete the Tkinter widgets, by using the various elements of widgets like buttons, labels, frames etc.
We could hide the Tkinter widgets by calling pack_forget() method to make the widgets invisible. We need to call the pack() method again to pack the widget to make it visible, or to recover it. We can also delete Tkinter widgets permanently by calling the destroy() method in this section.
Example 1: Hide and Recover the button in Tkinter using forget_pack() and pack() method.
Syntax:
widget.forget_pack()
Widget can be any valid widget which is visible.
Python3
from tkinter import *
root = Tk()
def hide_button(widget):
widget.pack_forget()
def show_button(widget):
widget.pack()
B1 = Button(root, text = "Button 1" )
B1.pack()
B2 = Button(root, text = "Button 2" , command = lambda : hide_button(B1))
B2.pack()
B3 = Button(root, text = "Button 3" , command = lambda : show_button(B1))
B3.pack()
root.mainloop()
|
Output:
Example 2: Hide and Recover the Label in Tkinter using forget_pack() and pack() method.
Python3
from tkinter import *
root = Tk()
label = Label(root, text = "LABEL" )
def hide_label():
label.pack_forget()
def recover_label():
label.pack()
B2 = Button(root, text = "Click To Hide label" , fg = "red" , command = hide_label)
B2.pack()
B1 = Button(root, text = "Click To Show label" ,
fg = "green" , command = recover_label)
B1.pack()
label.pack()
root.mainloop()
|
Output:
Example 3: Delete Tkinter widgets permanently by calling the destroy() method. We can use this method with any of the available widgets as well as with the main tkinter window.
Python3
from tkinter import *
root = Tk()
mylabel = Label(root, text = "GeeksforGeeks" )
mylabel.pack()
def delete_label():
mylabel.destroy()
B1 = Button(root, text = "DELETE" , command = delete_label)
B1.pack()
root.mainloop()
|
Output:
Last Updated :
11 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...