Home > Mobile >  How to make a line that follows the mouse(It follows it only by direction and don't change it&#
How to make a line that follows the mouse(It follows it only by direction and don't change it&#

Time:04-29

https://www.youtube.com/watch?v=TOEi6T2mtHo&ab_channel=TheCodingTrain

18:09 How to do the same thing in Tkinter

what i tried

from multiprocessing.connection import wait
from pickle import PicklingError
from tkinter import *
import win32api
from sklearn import preprocessing
root = Tk()
canvas = Canvas(root,bg = "pink",height = "500" ,width="1000")
def UpdateLine():
    position = win32api.GetCursorPos()
    x = position[0]
    y = position[1]
    wx = root.winfo_x()
    wy = root.winfo_y()
    
    if x < wx  1000 and x > wx and y < wy   500 and y> wy:
        canvas.coords(Line1, 100, 200,x-100    3 ,y-200)
    root.after(1,UpdateLine)

def Create_Line(x, y, r, canvasName): #center coordinates, radius
    position = win32api.GetCursorPos()
    x = position[0]
    y = position[1]
    return canvasName.create_line(100,200,x,y)



Line1 = Create_Line(1,2,3,canvas)



canvas.pack()
root.after(1,UpdateLine)
root.mainloop()

I have tried to calculate the distance between the lines than doing some bad maths but still, it's not working(not working as I wanted) to make things more clear I want to rotate the line to the mouse(just rotating nothing else cause i already can make it rotate but when it rotates the size of the line will change with it) to be more more specific how to make lookAt function(It makes and object literally look at in another obejct)

CodePudding user response:

Solution

  • Find the x, y coordinates of mouse
  • Calculate unit vector in the direction of mouse
  • Give the vector a constant magnitude

Example

import tkinter as tk

root = tk.Tk()

cv = tk.Canvas(root, width=500, height=500)
cv.pack()

length = 100

def redraw(event):
    cv.delete("all")

    msx = event.x - 250
    msy = event.y - 250
    mag = (msx*msx   msy*msy) ** 0.5
    print(250, 250, (msx/mag*length) 250, (msy/mag*length) 250)

    cv.create_line(250, 250, (msx/mag*length) 250, (msy/mag*length) 250, fill="red")


cv.bind("<Motion>", redraw)
root.mainloop()
  • Related