Hide a Button in Tkinter

20,814

As pointed out in the comments you should use place_forget() for widgets that were set on the screen using place().

Same goes for pack() and grid(). You would use pack_forget() and grid_forget() respectively.

Here is a modified example of your code.

import tkinter as tk

class Example(tk.Tk):
    def __init__(self):
        super().__init__()
        canvas = tk.Canvas(self)
        canvas.pack()
        self.startGame = tk.Button(canvas, text="Start", background='white', font=("Helvetica"))
        self.startGame.place(x=150, y=100)
        self.startGame.bind('<Button-1>', self.hide_me)

    def hide_me(self, event):
        print('hide me')
        event.widget.place_forget()

if __name__ == "__main__":
    Example().mainloop()

That said you do not need a bind here. Simply use a lambda statement in your command like this:

import tkinter as tk

class Example(tk.Tk):
    def __init__(self):
        super().__init__()
        canvas = tk.Canvas(self)
        canvas.pack()
        self.startGame = tk.Button(canvas, text="Start", background='white', font=("Helvetica"),
                                   command=lambda: self.hide_me(self.startGame))
        self.startGame.place(x=150, y=100)

    def hide_me(self, event):
        print('hide me')
        event.place_forget()

if __name__ == "__main__":
    Example().mainloop()
Share:
20,814
alyssaeliyah
Author by

alyssaeliyah

Shalom!

Updated on July 09, 2022

Comments

  • alyssaeliyah
    alyssaeliyah almost 2 years

    I want to hide a tkinter button but not when the user clicks it. I just want to hide it, at random times. How will I do that in Python? Below is the code I tried:

    self.startGame = Button(self.canvas, text="Start", background='white', command = self.startGame, font=("Helvetica"))
    self.startGame.place(x=770, y=400)
    

    Hiding it:

     self.startGame.bind('<Button-1>', self.hide_me)
    
     def hide_me(self, event):
        print('hide me')
        event.widget.pack_forget()
    

    It doesn't even get inside the hide_me function.