Python Tkinter | grid_location() and grid_size() method (original) (raw)

Last Updated : 21 Jun, 2022

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

from tkinter import * from tkinter.ttk import *

master = Tk()

def click(event):

`` x = event.x_root - f.winfo_rootx()

`` y = event.y_root - f.winfo_rooty()

`` z = f.grid_location(x, y)

`` print (z)

f = Frame(master)

f.pack()

b = Button(f, text = "Button" )

b.grid(row = 2 , column = 3 )

c = Button(f, text = "Button2" )

c.grid(row = 1 , column = 0 )

master.bind( "<Button-1>" , click)

mainloop()

https://media.geeksforgeeks.org/wp-content/uploads/20190626010302/ice_video_20190626-005104_edit_0.mp4

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

from tkinter import * from tkinter.ttk import *

master = Tk()

def grids(event):

`` x = f.grid_size()

`` print (x)

f = Frame(master)

f.pack()

b = Button(f, text = "Button" )

b.grid(row = 1 , column = 2 )

c = Button(f, text = "Button2" )

c.grid(row = 1 , column = 0 )

master.bind( "<Button-1>" , grids)

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)