In this post we will learn about Grid, Grid provide more flexible way of positioning and organizing the position of our widgets inside the tkinter application. Lets get started,
IN[1]
import tkinter as tk
from tkinter import ttk
try :
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
except :
pass
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.grid()
name_label = ttk.Label(named_frame, text = "Name : ")
name_label.grid()
name_entry = ttk.Entry(named_frame, width= 30, textvariable = user_name)
name_entry.grid()
name_entry.focus()
button_frame = ttk.Frame(root, padding = (20, 10))
button_frame.grid()
greet_button = ttk.Button(button_frame, text = "Greet", command = greet)
greet_button.grid()
quit_button = ttk.Button(button_frame, text = "Quit", command = root.destroy)
quit_button.grid()
root.mainloop()
OUT[1]
EXPLANATION
From above source code and snap we can see four widgets which are positioned using Grid not Pack inside a frame. As the name, Grid provide position in the form of the table with rows and column.
By passing in the column and row arguments inside the Grid class we can control the position in the form of 2D matrix structure thus providing the flexibility which Pack cannot provide. Like pack, just use grid on widgets and pass in the desired properties.