In this post we will learn how to work with frames in tkinter, how they work with other components and widgets. Lets get started,
IN[1]
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("300x200")
main = ttk.Frame(root)
main.pack(side = "left", expand = "True", fill = "both")
tk.Label(main, text = "Label Top", bg = "red", fg = "white").pack(side = "top", expand = "True", fill = "both")
tk.Label(main, text = "Label Top", bg = "red", fg = "white").pack(side = "top", expand = "True", fill = "both")
tk.Label(root, text = "Label Left", bg = "green", fg = "white").pack(side = "left", expand = "True", fill = "both")
root.mainloop()
OUT[1]
EXPLANATION
When frames are declared they act as a single container which will hold all the widgets inside that container. To understand it we will create two labels and place those two labels into that container, we will also place another label beside the container to demonstrate how container and labels works together.
main = ttk.Frame(root)
main.pack(side = "left", expand = "True", fill = "both")
First declare a variable named main and then use method Frame() in which parameter as root is passed since the frame will inside it.
tk.Label(main, text = "Label Top", bg = "red", fg = "white").pack(side = "top", expand = "True", fill = "both")
tk.Label(main, text = "Label Top", bg = "red", fg = "white").pack(side = "top", expand = "True", fill = "both")
To place the labels inside the frame just pass the frame variable inside the label method. Since the frame is defined before the Label Left, priority will be given to the frame resulting to place the Label Top one by one in the left then Label Left as displayed in the snapshot.