Tkinter - Pack in Python

Pack is one of the availble tools of arranging widgets in a tkinter window.

Here is a example of using pack. We have also used padx, and pady to control thre spacing of widgets.

#import Tkinter
import tkinter

#create a window
window = tkinter.Tk()

#Sets window title
window.title("Pack Example")

#Set variable to default value 
var1 = tkinter.StringVar(window)
var1.set("text.txt")
var2 = tkinter.IntVar(window)
var2.set(r"C:\temp")

#Create a Label
lbl1 = tkinter.Label(window, text="   File:    ")
lbl1.pack(padx=10, pady=0)

#Creates a text input box - set to A
input1 = tkinter.Entry(window,textvariable=var1)
input1.pack(padx=10, pady=0)

#Create a Label
lbl2 = tkinter.Label(window, text="   Location:    ")
lbl2.pack(padx=10, pady=0)

#Creates a text input box - set to B
input2 = tkinter.Entry(window,textvariable=var2)
input2.pack(padx=10, pady=0)

#Loops the tkinter window
window.mainloop()

Creates this window


Pack also lets to pack horizontally.

#import Tkinter
import tkinter

#create a window
window = tkinter.Tk()

#Sets window title
window.title("Pack Example")

#Set variable to default value 
var1 = tkinter.StringVar(window)
var1.set("text.txt")
var2 = tkinter.IntVar(window)
var2.set(r"C:\temp")

#Create a Label
lbl1 = tkinter.Label(window, text="   File:    ")
lbl1.pack(padx=10, pady=0, side=tkinter.LEFT)

#Creates a text input box - set to A
input1 = tkinter.Entry(window,textvariable=var1)
input1.pack(padx=10, pady=0, side=tkinter.LEFT)

#Create a Label
lbl2 = tkinter.Label(window, text="   Location:    ")
lbl2.pack(padx=10, pady=0, side=tkinter.LEFT)

#Creates a text input box - set to B
input2 = tkinter.Entry(window,textvariable=var2)
input2.pack(padx=10, pady=0, side=tkinter.LEFT)

#Loops the tkinter window
window.mainloop()
Creates this window







Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Must Read Articles

Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter _ Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines and labels.
Tkinter - Pack vs Grid vs Place - tkinter provides flexibility in how the layout the widgets. 
Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.