如何在Tkinter中获取按钮被点击时的坐标?
获取Tkinter按钮点击时的坐标实现方法
在Tkinter中,你可以通过绑定按钮的点击事件,在回调函数里调用按钮的坐标相关方法来获取位置,主要分两种坐标类型:
- 相对于父容器的坐标:使用
winfo_x()和winfo_y()方法,返回按钮左上角相对于父组件(比如窗口)的偏移量。 - 相对于屏幕的绝对坐标:使用
winfo_rootx()和winfo_rooty()方法,返回按钮左上角相对于整个屏幕的绝对位置。
完整示例代码
import tkinter as tk def get_button_coords(event): # 获取点击的按钮对象 button = event.widget # 相对父容器的坐标 rel_x = button.winfo_x() rel_y = button.winfo_y() # 屏幕绝对坐标 abs_x = button.winfo_rootx() abs_y = button.winfo_rooty() print(f"相对父容器坐标:x={rel_x}, y={rel_y}") print(f"屏幕绝对坐标:x={abs_x}, y={abs_y}") root = tk.Tk() root.title("获取按钮坐标") # 创建按钮并绑定点击事件 btn = tk.Button(root, text="点击我获取坐标") btn.pack(pady=20) btn.bind("<Button-1>", get_button_coords) root.mainloop()
代码说明
- 绑定
<Button-1>事件:监听鼠标左键点击按钮的动作,触发get_button_coords回调函数。 event.widget:通过事件对象获取被点击的按钮实例,确保多按钮场景下也能准确获取当前点击按钮的坐标。- 坐标方法:
winfo_x()/winfo_y():返回按钮相对于父组件的左上角像素坐标。winfo_rootx()/winfo_rooty():返回按钮相对于屏幕左上角的绝对像素坐标。
内容的提问来源于stack exchange,提问作者Amirmahdi Bayati
相关产品推荐
相关产品推荐

