How to Control Layout with grid() Method in Python


In this example, we will create a 5×5 button array using the grid() method and show the button label based on their positions.

2. Parameters

The grid() method places the control in a form or window according to the column of the table. The grid() method has the following parameters:

  1. row: This parameter sets the first few columns of the control in the table.
  2. column: This parameter sets the first few columns of the control in the table.
  3. columnspan: This parameter sets the number of columns that the control merges in the table.
  4. rowspan: This parameter sets the number of columns that the control merges in the table.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# gridLayout.py

from tkinter import *

# main window
win = Tk()
	
# create window
frame = Frame(win, relief=RAISED, borderwidth=2)
frame.pack(side=TOP, fill=BOTH, ipadx=5, ipady=5, expand=1)

# create buttons in a two-dimensional arrays
for i in range(5):
	for j in range(5):
		button_text = "(" + str(i) + "," + str(j)+ ")=Button " + str(i*5+j+1) 
		Button(frame, text=button_text).grid(row=i, column=j)

# start event loop for the window
win.mainloop()

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement