Tkinter - Creating a square that follows my mouse location

1.8k views Asked by At

I have to create a square around my pointer on the canvas. And I want that square to follow my pointer as I move it around.

from tkinter import *
root = Tk()
f = Frame(root)
f.pack()
c = Canvas(f,bg = "black")

while root:
    x = c.winfo_pointerx()
    y = c.winfo_pointery()
    c.create_rectangle(x,y,(x+10),(y+10),fill = "red")
    root.mainloop()

root.mainloop()

Now when I run this the rectangle doesn't load.

1

There are 1 answers

0
tobias_k On BEST ANSWER

Your method won't work, because once you call mainloop, it waits for the window to close, so it will never get past the first iteration of the loop. And if you remove the mainloop from the loop, it will never reach the mainloop after the (infinite) loop.

The proper way to do this is to use callback events. Also, you should move the rectangle, instead of creating a bunch of new ones. Try something like this:

def callback(event):
    x, y = event.x, event.y
    c.coords(rect, x - 10, y - 10, x + 10, y + 10)

root = Tk()
c = Canvas(root)
rect = c.create_rectangle(0, 0, 0, 0)
c.bind('<Motion>', callback)
c.pack()
root.mainloop()