EinSteini
EinSteini

Reputation: 13

Is there a possibility to "revive" buttons after .destroy()?

I am programming a game in Python and for this I want to have some buttons in tkinter that I can destroy and "revive" after this from another button click. Is it possible to "revive" destroyed Buttons?

I´ve tried to grid the Buttons again, but that didn't work.

def btnclick(event):
    b1.destroy()
def revive(event):
    b1.grid(row=0, column=4)
b1 = Button(root)
b2 = Button(root)
b1.bind("<Button-1>", btnclick)
b2.bind("<Button-1>", revive)
b1.grid(row=0, column=4)
b2.grid(row=1, column=4)

I thought that would put the button back on the screen, but I only get this error: _tkinter.TclError: bad window path name ".47822896"

Upvotes: 1

Views: 333

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36732

You cannot 'revive' an object that was destroyed; you can either re-create it, or, better yet, you can remove it from the GUI layout using grid_forget, and re-insert it later using the geometry manager grid.

here is a short example:

import tkinter as tk

def hide_b1():
    b1.grid_forget()

def show_b1():
    b1.grid(row=0, column=4)

root = tk.Tk()
b1 = tk.Button(root, text='b1', command=hide_b1)
b2 = tk.Button(root, text='b2', command=show_b1)
show_b1()
b2.grid(row=1, column=4)

root.mainloop()

Please note that tk.Buttons have an attribute command that you should take advantage of, and use, instead of custom bindings to events.

Upvotes: 1

Related Questions