Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

  from tkinter import *


class Main:

    def __init__(self, root):

        for i in range(0, 9):
            for k in range(0, 9):
                Button(root, text=" ").grid(row=i, column=k)


        root.mainloop()


root = Tk()

x = Main(root)

How do I delete a button when it is clicked if it isn't assigned to a variable ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

lambda is your friend.

When dealing with loops you have 2 major options. Both options use a lambda to maintain the values per button in a loop like this.

One is to have the button destroy itself:

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        for i in range(10):
            for k in range(10):
                btn = tk.Button(self, text='  ')
                btn.config(command=lambda b=btn: b.destroy())
                btn.grid(row=i, column=k)


if __name__ == '__main__':
    App().mainloop()

Or use a counter and a list. I prefer this list method as we can do a lot of things with a list like this if we need to.

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.btn_list = []
        counter = 0
        for i in range(10):
            for k in range(10):
                self.btn_list.append(tk.Button(self, text='  '))
                self.btn_list[-1].config(command=lambda c=counter: self.destroy_btn(c))
                self.btn_list[-1].grid(row=i, column=k)
                counter += 1

    def destroy_btn(self, ndex):
        self.btn_list[ndex].destroy()


if __name__ == '__main__':
    App().mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...