如何在 python Tkinter 中删除矩形?

How do I delete rectangles in python Tkinter?

我正在尝试删除我创建的旧矩形集。我的目标是拥有一个我可以按下的按钮,它将删除旧的矩形集、对数据进行排序并创建新的矩形。到目前为止,我已经了解了如何让按钮起作用,只是不知道如何删除它们。

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()

如果 canvas 上只有矩形,您可以使用 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)

这应该删除矩形。