Buttons have their own coordinate system according to the “grid_location” method?

旧街凉风 提交于 2019-12-01 03:51:28

问题


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.


回答1:


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.

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"])


来源:https://stackoverflow.com/questions/6101709/buttons-have-their-own-coordinate-system-according-to-the-grid-location-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!