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.
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 themainloop
from the loop, it will never reach themainloop
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: