In this lesson, we will discuss frames, pack() and layouts in Tkinter. Check our first Tkinter program - Introduction to GUI.

Code

from tkinter import *

root = Tk()

topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

root.mainloop()

Above code is used to divide the window in two frames namely Top stored in topFrame object and Bottom stored in bottomFrame object. Frame can be assumed as invisible containers used to store widgets. Frames help in deciding the layout of the window.

Adding buttons

Below section will explain adding buttons to a Tkinter window. Check the following code,

button1 = Button(topFrame, text="BUTTON 1", fg="red")
button2 = Button(topFrame, text="BUTTON 2", fg="green")
button3 = Button(topFrame, text="BUTTON 3", fg="blue")
button4 = Button(bottomFrame, text="BUTTON 4", fg="purple")
These lines will create 4 buttons, first 3 buttons will be in the top frame of the window i.e the upper half of the window in this case whereas the last button will be in the bottom frame of the window i.e the lower half of the window in this case. For every button above, 3 parameters are passed to the function Button that are :

1) Frame in which button must lie.
2) Label on the button.
3) Foreground i.e label color of the button.

Packing buttons

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack()
Above lines will be used to pack buttons in the window in their defined frames. In above code, 3 buttons are using pack() function with parameter side that is initialized to LEFT This will move the button to far left position in the frame in which that button arises.

Complete code

from tkinter import *

root = Tk()

topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

button1 = Button(topFrame, text="BUTTON 1", fg="red")
button2 = Button(topFrame, text="BUTTON 2", fg="green")
button3 = Button(topFrame, text="BUTTON 3", fg="blue")
button4 = Button(bottomFrame, text="BUTTON 4", fg="purple")

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack()

root.mainloop()

Output

output