单击后 tkinter 销毁按钮 [英] tkinter destroy button after click

查看:68
本文介绍了单击后 tkinter 销毁按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Python 创建了一个 Hangman 游戏,我想为我的代码创建一个 GUI.我创建了 26 个按钮(字母表中的每个字母一个).单击按钮后,我希望它被销毁.但是我不知道如何定义要销毁的特定按钮.我试过 destroy() 来单击函数,但它只是删除了最后一个按钮 (z).

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

推荐答案

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

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

这篇关于单击后 tkinter 销毁按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆