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 and y 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 module from tkinter import * from tkinter.ttk import * # creating master window master = Tk() # This method is used to get the position # of the desired widget available in any # other widget def click(event): # Here retrieving the size of the parent # widget relative to master widget x = 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 widget z = f.grid_location(x, y) # printing position print (z) # Frame widget, will work as # parent for buttons widget f = Frame(master) f.pack() # Button widgets b = 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 mouse master.bind( "<Button-1>" , click) # infinite loop mainloop() |
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 module from tkinter import * from tkinter.ttk import * # creating master window master = Tk() # This method is used to get the size # of the desired widget i.e number of grids # available in the widget def grids(event): # Here, grid_size() method is used to get # the total number grids available in frame # widget x = f.grid_size() # printing (columns, rows) print (x) # Frame widget, will work as # parent for buttons widget f = Frame(master) f.pack() # Button widgets b = 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 mouse master.bind( "<Button-1>" , grids) # infinite loop mainloop() |
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)