When and how to use pack or grid layouts in tkinter?


Tkinter Pack geometry manager is the bounding box for all the widgets. It helps the parent widget to hold and display all the containing widgets in it. It is easy to use and we can display any widgets by using the pack() method. Additionally, pack manager has several other properties like side, fill, expand, anchor, and padding which can be used to style the widgets in an application.

There is another useful way to hold and represent the widgets in a twodimensional table that is divided into rows and columns. Each row and column is made up of a Cell and each cell represents a widget. Thus, in order to position the widgets and style the widgets, grid provides several options such as sticky, rowspan, columnspan, padding.

In this article, we will take two examples to understand the use of pack and grid layouts in tkinter.

Example

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x200")
#Create two frames each for pack and grid respectively
frame1 = Frame(win)
frame2= Frame(win)
# placing widgets top-down in frame1
Button(frame1, text='ALL IS WELL').pack(fill=X)
Button(frame1, text='BACK TO BASICS').pack(fill=X)
Button(frame1, text='CATCH ME IF U CAN').pack(fill=X)
#Placing Widgets side by side
Button(frame1, text='LEFT').pack(side=LEFT)
Button(frame1, text='CENTER').pack(side=LEFT)
Button(frame1, text='RIGHT').pack(side=LEFT)
frame1.pack()
win.mainloop()

Output

Executing the above code will display a window with some buttons defined using pack manager.

Example

Now, let us take another example to understand the grid geometry manager.

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x200")
#Create frames each for pack and grid respectively
frame2= Frame(win)
#Create a Label in frame2
Label(frame2, text="Username").grid(row=0, sticky=W)
Label(frame2, text="Password").grid(row=1, sticky=W)
#Create an Entry Widget in Frame2
Entry(frame2).grid(row=0, column=1, sticky=E)
Entry(frame2).grid(row=1, column=1, sticky=E)
#Create Button in Frame2
Button(frame2, text="Login").grid(row=2, column=1, sticky=E)
frame2.pack()
win.mainloop()

Output

Executing the above code will display a window with username, password entry widgets, and a button.

Updated on: 16-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements