Buttons have their own coordinate system according to the quot;grid_locationquot; method?(根据“grid_location,按钮有自己的坐标系.方法?)
问题描述
我正在尝试使用 Tkinter 中 Grid Geometry Manager 中的 grid_location
方法,但似乎我做错了什么.
I'm trying to use the grid_location
method, from the Grid Geometry Manager, in Tkinter, but it seems that I'm doing something wrong.
这是我的代码:
from tkinter import *
root = Tk()
b=Button(root, text="00")
b.grid(row=0, column=0)
b2=Button(root, text="11")
b2.grid(row=1, column=1)
b3=Button(root, text="22")
b3.grid(row=2, column=2)
b4=Button(root, text="33")
b4.grid(row=3, column=3)
b5=Button(root, text="44")
b5.grid(row=4, column=4)
def mouse(event):
print(event.x, event.y)
print(root.grid_location(event.x, event.y))
root.bind("<Button-1>", mouse)
root.mainloop()
当我在按钮外部单击时,它可以工作,但是当我在任何按钮内部单击时,似乎每个按钮都有自己的坐标系.所以,每个按钮都在 (0, 0) 单元格上,尽管在代码中,它们都在规则网格上.
When I click outside the Buttons, it works, but when I click inside of any Button, it seems that each button has its own coordinate system. So, each button is on the (0, 0) cell, despite that in the code, they are on a regular grid.
推荐答案
你说得对,每个按钮都有自己的坐标系".不过,更准确地说,event.x
和 event.y
值是相对于与事件关联的小部件而不是小部件的父窗口或根窗口.
You are correct that each button "has it's own coordinate system". More accurately, though, the event.x
and event.y
values are relative to the widget associated with the event rather than the widget's parent or the root window.
如果您确实需要小部件所在的行和列,可以使用 grid_info
来获取与事件关联的小部件的行和列.例如:
If you really do need the row and column that the widget is in you can use grid_info
to get the row and column of the widget associated with the event. For example:
def mouse(event):
grid_info = event.widget.grid_info()
print("row:", grid_info["row"], "column:", grid_info["column"])
这篇关于根据“grid_location",按钮有自己的坐标系.方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据“grid_location",按钮有自己的坐标系.方法?


基础教程推荐
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01