I'm trying to delete the old set of rectangles I created. My goal is to have a button that I can press that will delete the old set of rectangles, sort the data, and create new rectangles. I've so far made sense of how to get the button to work I just don't understand how to delete them.
import tkinter as tk
import random
class main():
def __init__(self):
self.root = tk.Tk()
self.w = tk.Canvas(self.root, width=1000, height=1000)
self.rectangle = self.w.create_rectangle(5, 80, 1000, 1000, fill="white")
self.text = tk.StringVar()
self.label = tk.Label(self.w, text = "Click the button to sort the data.")
self.label2 = tk.Label(self.w, textvariable = self.text)
self.button = tk.Button(self.w, text="Press to search", command=self.click)
self.label.pack()
self.label.place(x=5,y=5)
self.label2.pack()
self.label2.place(x=130,y=25)
self.button.pack()
self.button.place(x=5,y=25)
self.random_list()
self.create_rectangles()
self.w.pack()
def click(self):
self.collection.sort()
self.w.delete(self.my_rect)
def random_list(self):
self.collection = []
for i in range(0,100):
n = random.randint(0,100)
self.collection.append(n)
print(self.collection)
def create_rectangles(self):
self.color = "yellow"
for i in range(100):
random_num = random.randint(80,1080)
self.my_rect = self.w.create_rectangle(5+(10*i),(random_num),10+(10*i),1000,fill=self.color)
if __name__ == "__main__":
search = main()
search.root.mainloop()
If the rectangles are the only shapes on the canvas, you could use self.w.delete(tk.ALL)
.
Otherwise, you will need to keep track of your rectangles in a list. Currently, you overwite self.my_rect
every time you create a rectangle. Here is a solution:
def click(self):
self.collection.sort()
for rect in self.rects:
self.w.delete(rect)
def create_rectangles(self):
self.color = "yellow"
self.rects = []
for i in range(100):
random_num = random.randint(80,1080)
rect = self.w.create_rectangle(5+(10*i),(random_num),10+(10*i),1000,fill=self.color)
self.rects.append(rect)
This should delete the rectangles.