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 ?
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 tkclass 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 tkclass App(tk.Tk):def __init__(self):super().__init__()self.btn_list = []counter = 0for 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 += 1def destroy_btn(self, ndex):self.btn_list[ndex].destroy()if __name__ == '__main__':App().mainloop()