Skip to content Skip to sidebar Skip to footer

Hide Label When A Button Is Clicked In Python

How could I hide an existing Label when a button is clicked in Python(Tkinter)?

Solution 1:

This really depends on the geometry manager you used. If you use

lbl = Tkinter.Label(parent)

to create the label, you will use one of the following to hide it.

lbl.grid_forget()
lbl.pack_forget()
lbl.place_forget()

edit (working example)

import tkinter

classMyClass(tkinter.Frame):
    def__init__(self,parent, *args, **kwargs):
        tkinter.Frame.__init__(self, parent, *args, **kwargs)

        self.btn = tkinter.Button(self,text='Don\'t push me',command=self.buttonCmd)
        self.btn.grid(row=0,column=0,sticky='nwes')
        self.lbl = tkinter.Label(self,text='Push it, it\'s fun')
        self.lbl.grid(row=0,column=1,sticky='nwes')

    defbuttonCmd(self,*args,**kwargs):
        self.lbl.grid_forget()

root = tkinter.Tk()
MyFrame = MyClass(root)
MyFrame.pack(expand='true',fill='both')
root.mainloop()

Solution 2:

Use can use grid_remove() to hide the label. like self.myLabel.grid_remove(). If you want to show it again then use self.myLabel.grid(). This will show widget on its original position on grid.

Solution 3:

If you use pack for you widget:

from tkinter import *

root = Tk()

def hide():
    label.pack_forget()

label = Label(root, text="The text")

label.bind("<Button-1>", hide)

label.pack()

root.mainloop()

If you use place to widget change label.pack_forget() to ```label.place_forget()

If you use grid to widget change label.pack_forget() to label.grid_forget()

Post a Comment for "Hide Label When A Button Is Clicked In Python"