如何在Tkinter窗口上显示实时鼠标位置

问题描述

我想知道是否有一种方法可以继续在tkinter窗口上显示实时鼠标的位置。我知道如何找到鼠标坐标。

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

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

解决方法

这将在鼠标位于tkinter窗口内时更新let tableEl = document.getElementById("tableId"); let index = 0; let colors = ["#e7eff6","#d0e1f9","#adcbe3"] for (let trEl of tableEl.rows) { trEl.style.backgroundColor = colors[index % colors.length]; index++; }

不需要使用win32api,tkinter内置了它。我们可以将函数绑定到Label的{​​{1}}键上,并使用给定的位置参数root来检索鼠标。

<Motion>
,

您可以使用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()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...