在tkinter中,可以通过绑定按钮的事件处理函数来获得鼠标位置。具体步骤如下:
import tkinter as tk
window = tk.Tk()
button = tk.Button(window, text="按钮")
def get_mouse_position(event):
x = event.x
y = event.y
print("鼠标位置:x =", x, "y =", y)
button.bind("<Button-1>", get_mouse_position)
window.mainloop()
完整的代码示例:
import tkinter as tk
def get_mouse_position(event):
x = event.x
y = event.y
print("鼠标位置:x =", x, "y =", y)
window = tk.Tk()
button = tk.Button(window, text="按钮")
button.bind("<Button-1>", get_mouse_position)
button.pack()
window.mainloop()
运行代码后,点击按钮时,控制台将输出鼠标的位置坐标。
领取专属 10元无门槛券
手把手带您无忧上云