如何在Tkinter中使用鼠标绘制一条直线?

3

我想创建一条直线并添加一个复位按钮,然后再从那里创建另一条直线。

目前我的代码可以用鼠标创建一条直线,但如果在完成第一条直线后单击,它会创建另一条直线。

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
1个回答

2
我的原始评论是:
您的点击函数总是为新行定义一个新的起点。您是否想要继续从上一行的末尾绘制一条线?那么,如果正在进行一条线,则必须抑制创建新的起点。也许可以使用 line_in_progress 标志或从 coords 中开始使用 None 值来指示下一个点击是新行的开始。
如果这就是您想要的,以下是简单的更改:
只需将您的 coords 初始化更改为:
coords = {"x":None,"y":0,"x2":0,"y2":0} # none flag indicates start of line

并将您的点击代码更改为:

def click(e):
    
    if coords["x"] is None:
        # 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'))
    else:
        coords["x"] = coords["x2"]
        coords["y"] = coords["y2"]        
        coords["x2"] = e.x
        coords["y2"] = e.y
        l = lines.append(canvas.create_line(coords["x"],coords["y"],coords["x2"],coords["y2"], width=5, fill='red'))

如果你想让下一次点击实际上开始一个全新的行,请在点击之前设置coords["x"]=None(也许是用另一个按钮,或者右键单击)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接