Skip to content Skip to sidebar Skip to footer

Drawing Straight Lines On A Tkinter Canvas With Grid On Python With Mouse

so currently I am working on a program that will allow origami artists to create crease patterns on their computer using this program. So far I have a program that draws a grid on

Solution 1:

My solution is to only let the user draw one line at a time. That is, as the mouse moves you don't keep creating new lines. Instead, modify the existing line.

For example, you could make it so that when the user clicks and then moves the mouse, no matter where the mouse is, only a single line is drawn from where they clicked to the current position. That will force the line to always be as straight as possible.

I started with your code and made as few changes as possible to show how this might work. If you click, drag, click, drag, click, etc, it will draw only one line segment between each click. If you want to start a new line completely disconnected from the current line, press the escape key.

In the code, the variable current contains the id of the line currently being drawn. When you press escape, this is reset to None. Whenever you click the mouse, a new line is started either from the end of current or the current mouse position. During a motion, we merely reset the endpoint of the current line.

from tkinter import *

current = NonedefDrawGrid(drawing_area, line_distance):

   for x inrange(line_distance,600,line_distance):
       drawing_area.create_line(x, 0, x, 600, fill="#d3d3d3")

   for y inrange(line_distance,600,line_distance):
       drawing_area.create_line(0, y, 600, y, fill="#d3d3d3")

defmain():
    root = Tk()
    drawing_area = Canvas(root, width=600, height=600, bg='white')
    drawing_area.pack()
    DrawGrid(drawing_area, 10)
    drawing_area.bind("<Escape>", reset)
    drawing_area.bind("<Motion>", motion)
    drawing_area.bind("<ButtonPress-1>", Mousedown)

    root.mainloop()

defreset(event):
    global current
    current = NonedefMousedown(event):
    global current

    event.widget.focus_set()  # so escape key will workif current isNone:
        # the new line starts where the user clicked
        x0 = event.x
        y0 = event.y

    else:
        # the new line starts at the end of the previously# drawn line
        coords = event.widget.coords(current)
        x0 = coords[2]
        y0 = coords[3]

    # create the new line
    current = event.widget.create_line(x0, y0, event.x, event.y)

defmotion(event):
    if current:
        # modify the current line by changing the end coordinates# to be the current mouse position
        coords = event.widget.coords(current)
        coords[2] = event.x
        coords[3] = event.y

        event.widget.coords(current, *coords)

main()

Post a Comment for "Drawing Straight Lines On A Tkinter Canvas With Grid On Python With Mouse"