Home > Mobile >  How to create just one straight line with mouse on tkinter?
How to create just one straight line with mouse on tkinter?

Time:10-06

I want to create just one straight line and also add some button to reset it, and from there, create another one.

Currently my code creates one straight lime with the mouse, but if after I finished the first line I click it creates another line.

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

CodePudding user response:

My original comment was:

Your click function always defines a new start point for a new line. Are you saying you want to draw a line continuing from the end of the previous line? Then you have to suppress the creation of a new start point if you have a line in progress. Perhaps using a line_in_progress flag or starting out with None values in coords to indicate the next click is a start of a new line.

If that's what you wanted, here's easy changes:

Just change your coords initialization to:

coords = {"x":None,"y":0,"x2":0,"y2":0} # none flag indicates start of line

and change your click code to:

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

And when you want the next click to actually start a brand new line, just set coords["x"]=None before clicking (perhaps with another button, or maybe a right-click)

  • Related