In this post we will revamp our Greeting App which we wrote in the earlier post. Earlier we only used labels but now will use frames to contain those labels. Lets get started,
IN[1]
import tkinter as tk
from tkinter import ttk
def greet():
print(f"Welcome, {name_entry.get() or 'World'}")
root = tk.Tk()
user_name = tk.StringVar()
root.title("Greeting App")
named_frame = ttk.Frame(root, padding = (20, 10, 20, 0))
named_frame.pack(fill = "both")
name_label = ttk.Label(named_frame, text = "Name : ")
name_label.pack(side = "left", padx = (0, 10))
name_entry = ttk.Entry(named_frame, width= 30, textvariable = user_name)
name_entry.pack(side = "left")
name_entry.focus()
button_frame = ttk.Frame(root, padding = (20, 10))
button_frame.pack(fill = "both")
greet_button = ttk.Button(button_frame, text = "Greet", command = greet)
greet_button.pack(side = "left", fill = "x", expand = True)
quit_button = ttk.Button(button_frame, text = "Quit", command = root.destroy)
quit_button.pack(side = "right", fill = "x", expand = True)
root.mainloop()
OUT[1]
EXPLANATION
If we remember our earlier program we had 4 elements a label, entry and 2 buttons. Now we will create 2 frames, one is to hold both label and entry the other is to hold both the buttons. To do that we will create 2 frames
named_frame
button_frame
named_frame = ttk.Frame(root, padding = (20, 10, 20, 0))
named_frame.pack(fill = "both")
name_label = ttk.Label(named_frame, text = "Name : ")
name_label.pack(side = "left", padx = (0, 10))
name_entry = ttk.Entry(named_frame, width= 30, textvariable = user_name)
name_entry.pack(side = "left")
name_entry.focus()
We first declared named_frame and it has side as top(by default), when we pass this frame to our label and entry it is given top priority by placing then on the top inside which it contains label and entry, they are placed side by side (side is left).
button_frame = ttk.Frame(root, padding = (20, 10))
button_frame.pack(fill = "both")
greet_button = ttk.Button(button_frame, text = "Greet", command = greet)
greet_button.pack(side = "left", fill = "x", expand = True)
quit_button = ttk.Button(button_frame, text = "Quit", command = root.destroy)
quit_button.pack(side = "right", fill = "x", expand = True)
Next we will use button_frame to contain both the buttons(greet and quit), this container is given second priority so it will be placed at the button of the first container. Inside it Greet button will be placed left and Quit button will be placed right. By using frames we can smartly manage positioning of the labels and buttons.