单击

时间:2016-06-15 15:50:14

标签: python python-3.x tkinter

我为python创建了Hangman游戏,我想为我的代码创建gui。我尝试创建26个按钮(每个字母对应一个字母)。点击按钮后,我想要将其销毁。但我不知道如何定义特定按钮来销毁。我已经尝试使用destroy()来单击函数,但它只是删除了最后一个按钮(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()

1 个答案:

答案 0 :(得分:2)

您可以将command的分配与另一行分开,以便您可以将按钮小部件本身的引用传递给click()函数:

...
    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()