-1

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!

PradMaster
  • 83
  • 10

2 Answers2

3

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()
Mandera
  • 2,647
  • 3
  • 21
  • 26
  • 1
    Why are you calling `__setitem__`? That's not designed to be called externally. You should use the standard `configure` method (`label.configure(text=...)` – Bryan Oakley Aug 19 '20 at 14:30
  • Ah I've always used `label["text"] = ...`, but since I wanted my example to be compact with a `lambda` I assumed I had to use `__setitem__`. I'll change it to `configure`, thanks! – Mandera Aug 19 '20 at 14:41
  • 1
    You could use `label["text"]` here if you want, and would actually be slightly more compact. Personally I prefer `configure`. – Bryan Oakley Aug 19 '20 at 14:44
0

You can use after() to periodically get the mouse coordinates and update the label.

Below is an example:

import tkinter as tk
import win32api

root = tk.Tk()

mousecords = tk.Label(root)
mousecords.place(x=0, y=0)

def show_mouse_pos():
    x, y = win32api.GetCursorPos()
    #x, y = mousecords.winfo_pointerxy() # you can also use tkinter to get the mouse coords
    mousecords.config(text=f'x : {x}, y : {y}')
    mousecords.after(50, show_mouse_pos) # call again 50ms later

show_mouse_pos() # start the update task
root.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34