如何用python绘制矩形?

时间:2019-06-13 15:03:21

标签: python tkinter

我想在使用此代码的图像上绘制一个矩形:

import Tkinter as tk

class draw_rect(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.x = self.y = 0
        self.canvas = tk.Canvas(self, width=400, height=400,cursor="cross")
        self.canvas.pack(side="top", fill="both", expand=True)
        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.canvas.bind("<ButtonRelease-1>",         self.on_button_release)

    def on_button_press(self, event):
        self.x = event.x
        self.y = event.y

    def on_button_release(self, event):
        x0,y0 = (self.x, self.y)
        x1,y1 = (event.x, event.y)

        self.canvas.create_rectangle(x0,y0,x1,y1, fill="RED")

if __name__ == "__main__":
    app = draw_rect()
    app.mainloop()

问题是它绘制了多个矩形,我想如果我画一个新的矩形,则删除前一个矩形。 我还想保存矩形坐标(x0,x1,y0,y1),以便以后使用。 谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用canvas.delete("all")进行清除,并且坐标已保存在变量中。

def on_button_press(self, event):
    self.x = event.x
    self.y = event.y
    self.canvas.delete("all")

def on_button_release(self, event):
    x0,y0 = (self.x, self.y)
    x1,y1 = (event.x, event.y)

    self.canvas.create_rectangle(x0,y0,x1,y1, fill="RED")

    print(x0,y0,x1,y1)  # You can write to file, or store as lists or do w/e with these