2 回答

TA貢獻1773條經驗 獲得超3個贊
這只會在Label鼠標位于 tkinter 窗口內時更新:
無需使用 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()

TA貢獻1804條經驗 獲得超2個贊
您可以使用它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()
添加回答
舉報