簡體   English   中英

如何在 tkinter window 上顯示活動鼠標 position

[英]How to show live mouse position on tkinter window

我想知道是否有辦法在 tkinter window 上繼續顯示活動鼠標 position。 我知道如何找到鼠標坐標。

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

但是我需要 label 在鼠標移動時不斷更新。 幫助將不勝感激謝謝!

只會在鼠標位於 tkinter window 內部時更新Label

無需使用 win32api,tkinter 已內置。我們可以將 function 綁定到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()

您可以使用after()定期獲取鼠標坐標並更新 label。

下面是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM