Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add a margin to a tkinter window?
In tkinter, you can add margins to windows and widgets using several approaches. The most common methods involve the pack() geometry manager with padx and pady parameters, or the grid() geometry manager with padding options.
Using pack() with Padding
The pack() method allows you to add margins using padx (horizontal) and pady (vertical) parameters −
# Import the required library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the size of the Tkinter window
win.geometry("700x350")
# Add a frame to set the margin of the window
frame = Frame(win, relief='sunken', bg="black")
frame.pack(fill=BOTH, expand=True, padx=10, pady=20)
# Add a label widget
label = Label(frame, text="Welcome to Tutorialspoint",
font=('Helvetica', 15, 'bold'), bg="white")
label.pack(pady=30)
win.mainloop()
Using grid() with Padding
The grid() geometry manager provides more precise control over margins using padx, pady, and sticky options −
from tkinter import *
# Create main window
win = Tk()
win.geometry("700x350")
win.title("Grid Margin Example")
# Configure grid weights for responsive layout
win.grid_rowconfigure(0, weight=1)
win.grid_columnconfigure(0, weight=1)
# Add a frame with grid and padding
frame = Frame(win, bg="lightblue", relief='raised', bd=2)
frame.grid(row=0, column=0, padx=20, pady=15, sticky='nsew')
# Add label inside frame
label = Label(frame, text="Grid Layout with Margins",
font=('Arial', 14, 'bold'), bg="white")
label.grid(row=0, column=0, padx=15, pady=25)
win.mainloop()
Internal vs External Padding
You can control both internal padding (inside widgets) and external padding (between widgets) −
from tkinter import *
win = Tk()
win.geometry("600x300")
win.configure(bg="gray")
# External padding: space around the frame
outer_frame = Frame(win, bg="blue")
outer_frame.pack(padx=30, pady=20, fill=BOTH, expand=True)
# Internal padding: space inside the frame
inner_label = Label(outer_frame, text="Padded Content",
font=('Times', 16), bg="yellow")
inner_label.pack(ipadx=20, ipady=10) # Internal padding
win.mainloop()
Comparison of Padding Options
| Parameter | Purpose | Usage |
|---|---|---|
padx |
External horizontal margin | Space around widget |
pady |
External vertical margin | Space around widget |
ipadx |
Internal horizontal padding | Space inside widget |
ipady |
Internal vertical padding | Space inside widget |
Conclusion
Use padx and pady with pack() or grid() to add margins around tkinter widgets. For internal spacing, use ipadx and ipady parameters.
Advertisements
