Reputation: 2244
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.
Upvotes: 5
Views: 39856
Reputation: 15226
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()
Upvotes: 5