How to show and hide widgets in Tkinter?

TkinterPythonGUI-Programming

Tkinter is a Python library which is used to create and develop GUI-based applications.Let us suppose that we have to create an application such that we can show or hide the widgets.

  • In order to display/show the widget, use pack() geometry manager
  • To hide any widget from the application, use pack_forget() method.

Example

Let us take this example to understand how to show/hide widgets −

# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window
win.geometry("700x350")

# Define the style for combobox widget
style = ttk.Style()
style.theme_use('xpnative')

# Define a function to show/hide widget
def show_widget():
   label.pack()
def hide_widget():
   label.pack_forget()
   b1.configure(text="Show", command=show_widget)

# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Aerial 11'))
label.pack(pady=30)

# Add a Button widget
b1 = ttk.Button(win, text="Hide", command=hide_widget)
b1.pack(pady=20)

win.mainloop()

Output

Running the above code will open a window that will have a Button to show/hide the widgets from the application.

Now, click the button to display/hide the label text from the window.

raja
Published on 08-Jun-2021 09:56:12
Advertisements