Tkinter is used to develop GUI (Graphical User Interface) applications. It supports a variety of widgets as well as a variety of widgets methods or universal widget methods.
grid_location() method -
This method returns a tuple containing (column, row) of any specified widget. Since this method is a widget method you cannot use it with master object ( or Tk() object). In order to use this method, you should first create a Frame and treat it as a parent (or master).
Syntax: widget.grid_location(x, y)
Parameters:
x andy are the positions, relative to the upper left corner of the widget (parent widget).
In below example, grid_location() is used to get the location of the widget in the Frame widget.
Python3# This imports all functions in tkinter modulefromtkinterimport*fromtkinter.ttkimport*# creating master windowmaster=Tk()# This method is used to get the position# of the desired widget available in any# other widgetdefclick(event):# Here retrieving the size of the parent# widget relative to master widgetx=event.x_root-f.winfo_rootx()y=event.y_root-f.winfo_rooty()# Here grid_location() method is used to# retrieve the relative position on the# parent widgetz=f.grid_location(x,y)# printing positionprint(z)# Frame widget, will work as# parent for buttons widgetf=Frame(master)f.pack()# Button widgetsb=Button(f,text="Button")b.grid(row=2,column=3)c=Button(f,text="Button2")c.grid(row=1,column=0)# Here binding click method with mousemaster.bind("<Button-1>",click)# infinite loopmainloop()
grid_size() method -
This method is used to get the total number of grids present in any parent widget. This is a widget method so one cannot use it with master object. One has to create a Frame widget.
Syntax: (columns, rows) = widget.grid_size()
Return Value: It returns total numbers of columns and rows (grids).
Below is the Python code-
Python3# This imports all functions in tkinter modulefromtkinterimport*fromtkinter.ttkimport*# creating master windowmaster=Tk()# This method is used to get the size# of the desired widget i.e number of grids# available in the widgetdefgrids(event):# Here, grid_size() method is used to get# the total number grids available in frame# widgetx=f.grid_size()# printing (columns, rows)print(x)# Frame widget, will work as# parent for buttons widgetf=Frame(master)f.pack()# Button widgetsb=Button(f,text="Button")b.grid(row=1,column=2)c=Button(f,text="Button2")c.grid(row=1,column=0)# Here binding click method with mousemaster.bind("<Button-1>",grids)# infinite loopmainloop()
Output:
Every time you click the mouse button it will return the same value until more widgets are not added OR number of rows and columns are not increased.
(3, 2)