Add padding to a Tkinter widget only on one side in Python

In this tutorial, we will learn about how to add padding and arrange the components in Tkinter.

We follow these steps to learn how to add padding to a widget.

  1. We first create a Tkinter object.
  2. We add geometry to the object.
  3. Now we should create a widget into this window.
  4. Now we will add padding to this widget using the grid.
  5. Now add this object to mainloop.

Grid function:

grid(padx(l,r),pady(t,b))

l=Padding from left.

r=Padding from right.

t=Padding from top.

b=Padding from bottom.

Let’s go with 2 Examples one is the top other is on left.

Example 1:

Code:

#import the required librearies like tkinter
from tkinter import *

#Now create a object of tkinter
tkobj = Tk()

tkobj.title("Codespeedy")

#adding geometry to the window
tkobj.geometry("400x400")

#creating a label
sa = Label(tkobj,text="Welcome to Codespeedy")
sa.grid(padx=(120,0),pady=(0,0))

sa.mainloop()

Output:

Add padding to a Tkinter widget only on one side in Python

Example 2:

Code:

#import the required librearies like tkinter
from tkinter import *

#Now create a object of tkinter
tkobj = Tk()

tkobj.title("Codespeedy")

#adding geometry to the window
tkobj.geometry("400x400")

#creating a label
sa = Label(tkobj,text="Welcome to Codespeedy")
sa.grid(padx=(0,0),pady=(200,0))

sa.mainloop()

Output:

Add padding to a Tkinter widget only on one side in Python

Leave a Reply

Your email address will not be published.