按钮根据“grid_location”具有自己的坐标系。方法?
我正在尝试使用 Tkinter 中网格几何管理器中的 grid_location 方法,但似乎我做错了。
这是我的代码:
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) 单元格上,尽管在代码中它们位于常规网格上。
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.
Here's my code:
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()
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是正确的,每个按钮“都有自己的坐标系”。不过,更准确地说,
event.x
和event.y
值是相对于与事件关联的窗口小部件,而不是相对于窗口小部件的父窗口或根窗口。如果您确实需要小部件所在的行和列,则可以使用 grid_info 来获取与事件关联的小部件的行和列。例如:
You are correct that each button "has it's own coordinate system". More accurately, though, the
event.x
andevent.y
values are relative to the widget associated with the event rather than the widget's parent or the root window.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: