Skip to content Skip to sidebar Skip to footer

How Do I Move An Object On The Screen Using The Mousex And Mousey Coordinates In Tkinter

I am trying to move the green object called char relative to the mouse x and mouse y coordinates but I don't know how. Can anyone help me? In case you are wondering i am trying to

Solution 1:

To move the green circle with the mouse, you need to bind the position of the circle to mouse motion event. Here is an example where the circle is always centered on the mouse when the mouse is in the canvas:

from tkinter import *

root = Tk()

canvas = Canvas(root)
canvas.pack(fill="both", expand=True)

char = canvas.create_oval(400,400,440,440,fill="green")

def follow_mouse(event):
    """ the center of char follows the mouse """
    x, y = event.x, event.y
    canvas.coords(char, x - 20, y - 20, x + 20, y + 20)

# bind follow_mouse function to mouse motion events
canvas.bind('<Motion>', follow_mouse)

root.mainloop()

Post a Comment for "How Do I Move An Object On The Screen Using The Mousex And Mousey Coordinates In Tkinter"