Marty
Marty

Reputation: 113

tkinter destroy button after click

I created a Hangman game for Python and I want to create a GUI for my code. I created 26 buttons (one for each letter in the alphabet). After I click the button, I want it to be destroyed. But I don't know how to define the specific button to be destroyed. I have tried destroy() to click function but it just deletes the last button(z).

from tkinter import *
import string
class LetterButtons:

    def __init__(self, master):
        self.master = master
        self.frame_let = Frame(master)
        self.frame_let.grid()
        alphabet = string.ascii_uppercase
        for l in alphabet:
            self.button = Button(self.frame_let, text=l, bg='orange', width=5,
                                 command=lambda idx=l: self.click(idx))
            self.button.grid()

    def click(self, idx):
        print(idx)
        # here is another function what handle "idx" variable



root = Tk()

lett = LetterButtons(root)

root.mainloop()

Upvotes: 4

Views: 13835

Answers (1)

MrAlexBailey
MrAlexBailey

Reputation: 5289

You can separate out the assignment of command to another line so that you can pass a reference of the button widget itself to your click() function:

...
    for l in alphabet:
        self.button = Button(self.frame_let, text=l, bg='orange', width=5)
        self.button['command'] = lambda idx=l, binst=self.button: self.click(idx, binst)
        self.button.grid()

def click(self, idx, binst):
    print(idx)
    binst.destroy()

Upvotes: 5

Related Questions