How to set padding of all widgets inside a window or frame in Tkinter?

TkinterPythonGUI-Programming

Padding enhances the layout of the widgets in an application. While developing an application in Tkinter, you can set the padding in two or more ways. The geometry manager in Tkinter allows you to define padding (padx and pady) for every widget (label, text, button, etc). To set the application component and its properties look and feel consistent, you can define the values in a variable. The values can be further used to define the padding of the widgets. Let us understand this with an example.

Example

In the following example, we will create a frame inside which the widgets are defined. To make sure the look and feel of the widgets are consistent, we can grab the values from the variable to use it in place of padding values.

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")

# Define padding values in variables
px=30
py=30

# Create a frame widget
frame=Frame(win, width=40, height=65, bg="blue")

# Create a label widget
label=Label(frame, text="A Labeled Widget", font=('Arial 15 bold'), bg="skyblue")
label.pack(padx=px, pady=py)
frame.pack(padx=px, pady=py)

win.mainloop()

Output

Running the above code will display a window with a Label widget inside a frame.

The variables "px" and "py" are used to define the values of padding. Try changing the value of the padding from variables itself.

raja
Published on 22-Dec-2021 10:42:47

Advertisements