How to delete a button that is made by a loop

2024/10/10 1:24:51
  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 ?

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 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()
https://en.xdnf.cn/q/118513.html

Related Q&A

Invalid array shape with neural network using Keras?

Currently studying the Deep Learning with Python book by Francios Chollet. I am very new to this and I am getting this error code despite following his code verbatim. Can anyone interpret the error mes…

How to download PDF files from a list of URLs in Python?

I have a big list of links to PDF files that I need to download (500+) and I was trying to make a program to download them all because I dont want to manually do them. This is what I have and when I tr…

Training on GPU much slower than on CPU - why and how to speed it up?

I am training a Convolutional Neural Network using Google Colabs CPU and GPU. This is the architecture of the network: Model: "sequential" ____________________________________________________…

Check list item is present in Dictionary

Im trying to extend Python - Iterate thru month dates and print a custom output and add an addtional functionality to check if a date in the given date range is national holiday, print "NH" a…

a list of identical elements in the merge list

I need to merge the list and have a function that can be implemented, but when the number of merges is very slow and unbearable, I wonder if there is a more efficient way Consolidation conditions:Sub-…

How To Get A Contour Of More/Less Of The Expected Area In OpenCV Python

I doing some contour detection on a image and i want to find a contour based on a area that i will fix in this case i want the contour marked in red. So i want a bounding box around the red contour Fol…

Storing output of SQL Query in Python Variable

With reference to this, I tried modifying my SQL query as follows:query2 ="""insert into table xyz(select * from abc where date_time > %s and date_time <= ( %s + interval 1 hour))&…

file modification and creation

How would you scan a dir for a text file and read the text file by date modified, print it to screen having the script scan the directory every 5 seconds for a newer file creadted and prints it. Is it …

How to share a file between modules for logging in python

I wanted to log messages from different module in python to a file. Also I need to print some messages to console for debugging purpose. I used logger module for this purpose . But logger module will l…

Dont understand how this example one-hot code indexes a numpy array with [i,j] when j is a tuple?

I dont get how the line: results[i, sequence] = 1 works in the following.I am following along in the debugger with some sample code in a Manning book: "Deep Learning with Python" (Example 3.5…