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!
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()
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.