Search code examples
pythontkintermouse-position

How to show live mouse position on tkinter window


i would like to know if there was a way to keep showing the live mouse position on a tkinter window. I know how to find mouse coordinates.

x, y = win32api.GetCursorPos()
mousecords = Label(self.root, text='x : ' + str(x) + ', y : ' + str(y))
mousecords.place(x=0, y=0)

But I need the label to keep updating as and when the mouse moves. Help will be appreciated Thank you!


Solution

  • This will only update the Label when the mouse is inside the tkinter window:

    No need to use win32api, tkinter has it built in. We can bind a function to root's <Motion> key and use the given positional argument event to retrieve the coordinates of the mouse.

    from tkinter import Tk, Label
    
    root = Tk()
    label = Label(root)
    label.pack()
    root.bind("<Motion>", lambda event: label.configure(text=f"{event.x}, {event.y}"))
    root.mainloop()