如何在 tkinter 上显示实时鼠标位置 window

How to show live mouse position on tkinter window

我想知道是否有办法在 tkinter window 上继续显示实时鼠标位置。我知道如何找到鼠标坐标。

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

但我需要标签在鼠标移动时不断更新。帮助将不胜感激 谢谢!

您可以使用after()定期获取鼠标坐标并更新标签。

下面是一个例子:

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()

这将 更新 Label 当鼠标在 tkinter 中时 window:

无需使用 win32api,tkinter 内置了它。我们可以将一个函数绑定到 root<Motion> 键,并使用给定的位置参数 event 来检索鼠标坐标。

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()