Do the buttons have their own coordinate system in accordance with the grid_location method?

I'm trying to use the grid_location method, from the Grid Geometry Manager, in Tkinter, but it seems like I'm doing something wrong.

Here is 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 go beyond the buttons, it works, but when I click inside any button, it seems that each button has its own coordinate system. Thus, each button is in the cell (0, 0), despite the fact that in the code they are on a regular grid.

+4
source share
1 answer

You are right that each button has its own coordinate system. More precisely, the values โ€‹โ€‹of event.x and event.y refer to the widget associated with the event, and not to the widget's parent element or root window.

If you really 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 instance:

 def mouse(event): grid_info = event.widget.grid_info() print("row:", grid_info["row"], "column:", grid_info["column"]) 
+6
source

All Articles