Search code examples
pythonbuttontkinterwidgetdestroy

How to destroy widgets?


I want in my if statement for it to destroy the buttons on my tkinter. I have tried a couple of methods and looked up a few and some i don't understand/too complicated. I have tried making the function create a new window but it isn't displaying.

def greenwin():
    global tkinter
    global Tk
    root = Tk()
    root.title("GAME OVER")
    root.geometry('387x387')
    gamelabel=Label(root,text="GAME OVER!GREENS
WIN!",width=33,height=15).place(x=150,y=150)
    root.mainloop
    return

I want a clear method of destroying widgets.I would like a function that destroys all these buttons for my tic tac toe.

but1=Button(root,text="",bg="white",width=11,height=5,command=colour1).place(x=0,y=0)
but2=Button(root,text="",bg="white",width=11,height=5,command=colour2).place(x=0,y=150)
but3=Button(root,text="",bg="white",width=11,height=5,command=colour3).place(x=0,y=300)
but4=Button(root,text="",bg="white",width=11,height=5,command=colour4).place(x=150,y=0)
but5=Button(root,text="",bg="white",width=11,height=5,command=colour5).place(x=150,y=150)
but6=Button(root,text="",bg="white",width=11,height=5,command=colour6).place(x=150,y=300)
but7=Button(root,text="",bg="white",width=11,height=5,command=colour7).place(x=300,y=0)
but8=Button(root,text="",bg="white",width=11,height=5,command=colour8).place(x=300,y=150)
but9=Button(root,text="",bg="white",width=11,height=5,command=colour9).place(x=300,y=300)
root.mainloop

Solution

  • Try this:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry("500x300+10+13")
    root.title("Test")
    
    b = tk.Button(root, text="click me")
    
    def onclick(evt):
        w = evt.widget
        w.destroy()
    
    b.bind("<Button-1>", onclick)
    
    b.pack()
    root.mainloop()