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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…