Tony Springs
Tony Springs

Reputation: 85

Destroy Specific Python Widgets Using Instance Number?

I am using a button to put 10 buttons on a canvas. when I run the button once, it makes the canvas and the ten buttons.

    for a in range(10):
        b=Button(canvas, text=str(a) + "but", font=A12B,
                 command=lambda : noButs())
        b.pack(side='right')

    def noButs():
        b.destroy()

however, if I click twice, it makes twenty buttons, and it will not destroy any of them.

Is there a way to remove specific widgets by name, or instance number?? or maybe get the number of the active canvas and destroy it?

Upvotes: 0

Views: 46

Answers (1)

Uri
Uri

Reputation: 68

You should put the buttons in a list, and then you can destroy them by index. Something like:

buttons = []
for a in range(10):
    b=Button(canvas, text=str(a) + "but", font=A12B,
             command=lambda : noButs())
    b.pack(side='right')
    buttons.append(b)

def noButs():
    for button in buttons:
        button.destroy()
        buttons = []

def deleteBut(index):
    buttons[index].destroy()
    del buttons[index]

Note that this changes the index for items after the one you delete.

If you prefer, you can use a dictionary, and give each button a name.

Just make sure you don't put buttons = [] every time you push your button. Do it outside of the button action (if you use a class add self.buttons).

Upvotes: 1

Related Questions