Showing and Hiding widgets in Tkinter?

TkinterPythonServer Side ProgrammingProgramming

Let us suppose that we have to create an application such that we can show as well as hide the widgets whenever we need.

  • The widgets can be hidden through pack_forget() method.

  • To show the hidden widgets, we can use the pack() method.

Both methods can be invoked using the lambda or anonymous function.

Example

#Import the required library
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Define the geometry of the window
win.geometry("650x450")

#Define function to hide the widget
def hide_widget(widget):
   widget.pack_forget()

#Define a function to show the widget
def show_widget(widget):
   widget.pack()

#Create an Label Widget
label= Label(win, text= "Showing the Message", font= ('Helvetica bold', 14))
label.pack(pady=20)

#Create a button Widget
button_hide= Button(win, text= "Hide", command= lambda:hide_widget(label))
button_hide.pack(pady=20)

button_show= Button(win, text= "Show", command= lambda:show_widget(label))
button_show.pack()

win.mainloop()

Output

Running the above code will display a window with two buttons “Show” and “Hide” which can be used to show and hide the widgets.

Now click on “Hide” button to hide the Label Text and “Show” to show the Label Text.

raja
Published on 26-Mar-2021 10:17:51
Advertisements