我正在尝试删除我创建的旧矩形集。我的目标是有一个可以按下的按钮,该按钮将删除旧的矩形集,对数据进行排序并创建新矩形。到目前为止,我已经理解了如何让按钮工作,我只是不明白如何删除它们。
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()
如果矩形是画布上唯一的形状,则可以使用self.w.delete(tk.ALL)
.
否则,您将需要跟踪列表中的矩形。目前,每次创建矩形时都会self.my_rect
智取。这是一个解决方案:
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)
这应该删除矩形。