[英]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.
我还想保存矩形坐标(x0,x1,y0,y1),以便以后使用。 Thank you.
谢谢。
You can use canvas.delete("all")
to clear, and the coordinates are already saved in a variable. 您可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.