简体   繁体   中英

how to draw a rectangle with python?

I want to draw a rectangle on the image I used this code :

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

the issue is it draws more than one rectangle, I want if I draw a new rectangle the previous one deleted. one more thing I want to save the rectangle coordinate (x0,x1,y0,y1) that I can use it later. Thank you.

You can use canvas.delete("all") to clear, and the coordinates are already saved in a variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM