📐 Unit-IV: Tkinter Layout & UI Components

Lecture 3: Layout Managers, Menus & Dialog Boxes

1. Introduction to Layout Management

In Tkinter, layout management is the process of organizing and positioning widgets within a container. Tkinter provides three geometry managers:

  • pack(): Packs widgets in a vertical or horizontal box
  • grid(): Organizes widgets in a table-like structure
  • place(): Places widgets at specific positions (not recommended for general use)
Best Practice: Avoid mixing pack() and grid() in the same container. Each container (like a frame) should use only one geometry manager.
2. The Pack Layout Manager

The pack() geometry manager organizes widgets in blocks before placing them in the parent widget.

Basic Pack Example

import tkinter as tk root = tk.Tk() root.title("Pack Layout Example") # Create and pack buttons btn1 = tk.Button(root, text="Button 1") btn1.pack() # Default side is 'top' btn2 = tk.Button(root, text="Button 2") btn2.pack(side="left") # Align to left btn3 = tk.Button(root, text="Button 3") btn3.pack(side="right") # Align to right # Fill and expand options btn4 = tk.Button(root, text="Button 4 (Fill X)") btn4.pack(fill="x", padx=5, pady=5) btn5 = tk.Button(root, text="Button 5 (Expand)") btn5.pack(expand=True, fill="both", padx=10, pady=10) root.mainloop()

Pack Options

  • side: Which side to pack the widget (TOP, BOTTOM, LEFT, RIGHT)
  • fill: Fill available space (X, Y, BOTH, NONE)
  • expand: Whether to expand to fill any extra space (True/False)
  • padx/pady: External padding
  • ipadx/ipady: Internal padding
  • anchor: Position within the allocated space (N, E, S, W, NE, etc.)
Pack Layout Preview
Button 1 (top)
Button 2 (left)
Button 3 (right)
Button 4 (fill x)
Button 5 (expand)
3. The Grid Layout Manager

The grid() geometry manager organizes widgets in a 2-dimensional table.

Basic Grid Example

import tkinter as tk root = tk.Tk() root.title("Grid Layout Example") # Configure grid weights root.grid_columnconfigure(1, weight=1) root.grid_rowconfigure(1, weight=1) # Create and place widgets using grid tk.Label(root, text="Username:").grid(row=0, column=0, sticky="e", padx=5, pady=5) tk.Entry(root).grid(row=0, column=1, sticky="we", padx=5, pady=5) tk.Label(root, text="Password:").grid(row=1, column=0, sticky="e", padx=5, pady=5) tk.Entry(root, show="*").grid(row=1, column=1, sticky="we", padx=5, pady=5) # Buttons frame btn_frame = tk.Frame(root) btn_frame.grid(row=2, column=0, columnspan=2, pady=10) tk.Button(btn_frame, text="Login").pack(side="left", padx=5) tk.Button(btn_frame, text="Cancel").pack(side="left", padx=5) # Span example tk.Label(root, text="Grid with column/row span").grid( row=3, column=0, columnspan=2, pady=10 ) root.mainloop()

Grid Options

  • row/column: Position in the grid (0-based)
  • rowspan/columnspan: Number of rows/columns to span
  • sticky: Alignment within the cell (N, E, S, W, or combinations)
  • padx/pady: External padding
  • ipadx/ipady: Internal padding
Grid Layout Preview
Username:
Password:
Grid with column/row span
Tip: Use grid_columnconfigure() and grid_rowconfigure() to make rows and columns expandable.
4. Creating Menus in Tkinter

Tkinter provides the Menu widget to create menu bars, pull-down menus, and popup menus.

Menu Example

import tkinter as tk from tkinter import messagebox def on_new(): print("New File") def on_about(): messagebox.showinfo("About", "Tkinter Menu Example\nVersion 1.0") root = tk.Tk() root.title("Menu Example") # Create a menu bar menubar = tk.Menu(root) root.config(menu=menubar) # File menu file_menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="New", command=on_new, accelerator="Ctrl+N") file_menu.add_command(label="Open...") file_menu.add_separator() file_menu.add_command(label="Exit", command=root.quit) # Edit menu edit_menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="Edit", menu=edit_menu) edit_menu.add_command(label="Cut") edit_menu.add_command(label="Copy") edit_menu.add_command(label="Paste") # Help menu help_menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="Help", menu=help_menu) help_menu.add_command(label="About", command=on_about) # Context menu context_menu = tk.Menu(root, tearoff=0) context_menu.add_command(label="Copy") context_menu.add_command(label="Paste") def show_context_menu(event): context_menu.post(event.x_root, event.y_root) # Bind right-click to show context menu root.bind("", show_context_menu) root.mainloop()

Menu Types

  • Menu Bar: Top-level menu (File, Edit, etc.)
  • Pull-down Menu: Appears when clicking a menu item
  • Context Menu: Appears on right-click
  • Tear-off Menu: Can be detached (disabled by default in modern apps)
5. Dialog and Message Boxes

Tkinter provides several standard dialog boxes through the tkinter.messagebox and tkinter.filedialog modules.

Message Boxes

from tkinter import messagebox # Show info message messagebox.showinfo("Information", "This is an info message") # Show warning messagebox.showwarning("Warning", "This is a warning message") # Show error messagebox.showerror("Error", "This is an error message") # Ask question (returns 'yes' or 'no') response = messagebox.askquestion("Confirm", "Are you sure?") if response == 'yes': print("User clicked Yes") # Ask yes/no/cancel (returns True/False/None) response = messagebox.askyesnocancel("Save Changes", "Do you want to save changes?") if response is True: print("Save changes") elif response is False: print("Don't save") else: print("Cancel")
Information
This is an info message

File Dialogs

from tkinter import filedialog from tkinter import messagebox def open_file(): file_path = filedialog.askopenfilename( title="Open File", filetypes=( ("Text files", "*.txt"), ("All files", "*.*") ) ) if file_path: messagebox.showinfo("File Selected", f"Selected: {file_path}") def save_file(): file_path = filedialog.asksaveasfilename( defaultextension=".txt", filetypes=( ("Text files", "*.txt"), ("All files", "*.*") ) ) if file_path: messagebox.showinfo("Save As", f"Will save to: {file_path}") # Example usage in a Tkinter app root = tk.Tk() tk.Button(root, text="Open File", command=open_file).pack(pady=10) tk.Button(root, text="Save As", command=save_file).pack(pady=10) root.mainloop()

Color Chooser

from tkinter import colorchooser def choose_color(): color = colorchooser.askcolor(title="Choose a color") if color[1]: # If a color was selected print(f"Selected color: {color[1]}") # color[0] contains RGB tuple, color[1] contains hex string # Example usage root = tk.Tk() tk.Button(root, text="Choose Color", command=choose_color).pack(pady=20) root.mainloop()
6. Practice Exercise

Text Editor Application

Create a simple text editor with the following features:

  1. A menu bar with File and Edit menus
  2. File menu should have: New, Open, Save, Save As, and Exit
  3. Edit menu should have: Cut, Copy, Paste, and Select All
  4. Add a text area with scrollbars
  5. Add a status bar showing line and column numbers
  6. Implement keyboard shortcuts (Ctrl+N, Ctrl+O, Ctrl+S, etc.)
  7. Add a context menu with common editing options

Hints:

  • Use Text widget for the text area
  • Use Menu for the menu bar and context menu
  • Use filedialog for file operations
  • Bind keyboard shortcuts using bind() method
  • Update status bar using after() method
Challenge: Add syntax highlighting for Python code using tags in the Text widget.