我想创建一条直线并添加一个复位按钮,然后再从那里创建另一条直线。
目前我的代码可以用鼠标创建一条直线,但如果在完成第一条直线后单击,它会创建另一条直线。
import tkinter as tk
from PIL import ImageTk
root = tk.Tk()
canvas = tk.Canvas(width = 600, height = 400)
canvas.pack(expand = tk.YES, fill = tk.BOTH)
coords = {"x":0,"y":0,"x2":0,"y2":0}
# keep a reference to all lines by keeping them in a list
lines = []
def click(e):
# define start point for line
coords["x"] = e.x
coords["y"] = e.y
# create a line on this point and store it in the list
l = lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"], width=5, fill='red'))
def drag(e):
# update the coordinates from the event
coords["x2"] = e.x
coords["y2"] = e.y
print(e.x, e.y)
# Change the coordinates of the last created line to the new coordinates
l = canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])
canvas.itemconfigure(l, fill="black")
canvas.bind("<ButtonPress-1>", click)
canvas.bind("<B1-Motion>", drag)
print(coords["x"],coords["y"],coords["x2"],coords["y2"])
root.mainloop()
line_in_progress
标志或在坐标中开始使用None
值来指示下一次点击是新行的开始。 - RufusVS