I’m trying to get the object to move in the direction of the mouse, but I’m not out of line, but I must have written something wrong.
from tkinter import *
def MouseMove(event):
x1, y1, x2, y2 = canvas.bbox(square)
canvas.move(square, event.x - x2, event.y - y2)
window = Tk()
window.geometry('800x600')
canvas = Canvas(window, width=50, height=50)
square = canvas.create_rectangle(10,10,20,20, fill="red")
canvas.place(x=200, y=50)
window.bind('<Motion>', MouseMove)
window.mainloop()
I need the object to move (aiming towards the cursor) within the canvas, but everything is tracked outside the canvas
I tried to solve it this way, but somehow an object in the same direction flies away fast
from tkinter import *
def MouseMove(event):
x1,y1,x2,y2 = canvas.bbox(square) # size object
c_x = x1 ((x2-x1)/2) # center object x
c_y = y1 ((y2-y1)/2) # center object y
pos_x = event.x # center mouse x
pos_y = event.y # center mouse y
del_x = 800/50 # window size difference and canvas x
del_y = 600/50 # window size difference and canvas y
can_x = int(event.x/del_x)# Mouse position detection in the canvas window
can_y = int(event.y/del_y)# Mouse position detection in the canvas window
if c_x != can_x and c_y != can_y:
i=0
j=0
if c_x < can_x:
i = -1
elif c_x > can_x:
i = 1
elif c_x == can_x:
i = 0
if c_y < can_y:
j = -1
elif c_y > can_y:
j = 1
elif c_y == can_y:
j = 0
canvas.move(square, -i, -j)
window1 = Tk()
window1.title("AIEyeGod")
window1.geometry('800x600')
window1.configure(bg='#E6E6FA')
canvas = Canvas(window1, width=50, height=50, bg='#E6E6FA')
square = canvas.create_rectangle(20,20,30,30, fill="red")
canvas.place(x=200, y=50)
window1.bind('<Motion>', MouseMove)
window1.mainloop()
but the object is out of bounds for some reason
CodePudding user response:
Тему можно закрывать, сам решил. Спасибо за намек relent95
from tkinter import *
def MouseMove(event):
x1,y1,x2,y2 = canvas.bbox(square)
c_x = x1 ((x2-x1)/2) 200
c_y = y1 ((y2-y1)/2) 50
pos_x = event.x
pos_y = event.y
if c_x != event.x and c_y != event.y:
i=0
j=0
if c_x < 245 < event.x:
i = -1
elif c_x > 206 > event.x:
i = 1
if c_y < 95 < event.y:
j = -1
elif c_y > 56 > event.y:
j = 1
canvas.move(square, -i, -j)
window1 = Tk()
window1.title("AIEyeGod")
window1.geometry('800x600')
window1.configure(bg='#E6E6FA')
canvas = Canvas(window1, width=50, height=50, bg='#E6E6FA')
square = canvas.create_rectangle(20,20,30,30, fill="red")
canvas.place(x=200, y=50)
window1.bind('<Motion>', MouseMove)
window1.mainloop()