Tkinter pack padx/pady parameter
When using the pack method, you can use the padx/pady parameter to set the distance between the control boundary and the container (think of it as the window boundary) or the distance between the control boundaries. In the default environment the distance between window controls is 1 pixel, if you want to have a moderate spacing you can set the parameter padx/pady, which stands for horizontal spacing/vertical spacing, to increase the spacing between components respectively.
Tkinter pack padx/pady Example#1
Add 10 pixels spacing above and below the lightblue Label
.
from tkinter import *
window = Tk()
window.title("apidemos.com")
lab1 = Label(window,text="lightyellow Label",
bg="lightyellow")
lab2 = Label(window,text="lightgreen Label",
bg="lightgreen")
lab3 = Label(window,text="lightblue Label",
bg="lightblue")
lab1.pack(fill=X) # Filling the X-axis packing and positioning assembly
lab2.pack(pady=10) # Increase y-axis by 10 pixels
lab3.pack(fill=X) # Filling the X-axis packing and positioning assembly
window.mainloop()
Output:
For the above program, if you add pady=10 to the lightyellow Label
label pack, the spacing between the lightyellow Label
label boundary and the upper container boundary will be 10, but the spacing between it and the lightgreen Label
label will be 20 because they affect each other.
Tkinter pack padx/pady Example#2
Add pady=10 to the lightyellow Label
pack.
from tkinter import *
window = Tk()
window.title("apidemos.com")
lab1 = Label(window,text="lightyellow Label",
bg="lightyellow")
lab2 = Label(window,text="lightgreen Label",
bg="lightgreen")
lab3 = Label(window,text="lightblue Label",
bg="lightblue")
lab1.pack(fill=X,pady=10) # Filling the X-axis packing and positioning assembly
lab2.pack(pady=10) # Increase y-axis by 10 pixels
lab3.pack(fill=X) # Filling the X-axis packing and positioning assembly
window.mainloop()
Output:
Tkinter pack padx/pady Example#3
Design three labels with a label width of 15 characters wide and a left and right border of the label with the container border of 50 pixels.
from tkinter import *
window = Tk()
window.title("apidemos.com")
lab1 = Label(window,text="lightyellow Label",
bg="lightyellow",width=15) # Set label width 15
lab2 = Label(window,text="lightgreen Label",
bg="lightgreen",width=15)
lab3 = Label(window,text="lightblue Label",
bg="lightblue",width=15)
lab1.pack(padx=50)
lab2.pack(padx=50)
lab3.pack(padx=50)
window.mainloop()
Output:
Tkinter pack padx/pady Example#4
Add 10 pixels spacing to the left and right of the lightgreen Label
.
from tkinter import *
window = Tk()
window.title("ch3_9")
lab1 = Label(window,text="lightyellow Label",
bg="lightyellow",width=15) # Set label width 15
lab2 = Label(window,text="lightgreen Label",
bg="lightgreen",width=15)
lab3 = Label(window,text="lightblue Label",
bg="lightblue",width=15)
lab1.pack(side=LEFT)
lab2.pack(side=LEFT,padx=10)
lab3.pack(side=LEFT)
window.mainloop()
Output: