Дополнительная библиотека не требуется.Вы можете просто привязать <Button-1>
к событию и рассчитать расстояние, используя event.x
и event.y
.
from tkinter import *
from random import randint
root = Tk()
root.configure(background='DeepSkyBlue4')
class DrawLine:
def __init__(self,master):
self.canvas = Canvas(master, width=500, height=500,bg="white")
self.canvas.bind("<Button-1>", lambda e: self._move(e.x,e.y))
self.previous_pos = None
self.total_length = 0
self.t = Label(master, text=f"Total Length: {self.total_length} pixels",font=('Arial',12),pady=5,bg="DeepSkyBlue4",fg="white")
self.t.pack()
self.canvas.pack()
self.random_position()
def _move(self,new_x,new_y):
self.canvas.create_oval(new_x + 5, new_y + 5, new_x - 5, new_y - 5, width=0, fill='red')
if self.previous_pos:
old_x, old_y = self.previous_pos
self.canvas.create_line(old_x, old_y, new_x, new_y, width=2)
self.total_length += ((new_x - old_x) ** 2 + (new_y - old_y) ** 2) ** (1 / 2)
self.t.config(text=f"Total Length: {round(self.total_length,2)} pixels")
self.previous_pos = (new_x, new_y)
def random_position(self):
self._move(randint(0,500),randint(0,500))
root.after(1000,self.random_position)
DrawLine(root)
root.mainloop()