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

Question:

I create a window with two buttons and set the padding of both of them.

from tkinter import *

window = Tk()
Button(window, text="Click Me").pack(padx=10, pady=10)
Button(window, text="Click Me").pack(padx=10, pady=10)
window.mainloop()

I want to remove padx and pady parameter from pack() and getting the same result. How can I do this?

Asked By: wannik

||

Answers:

You can’t do exactly what you want. There is no global configuration for defining the padx and pady values of pack in order to eliminate the need to explicitly include the values when calling pack. Though, you can put the values in variable so that if you want to change the value later, you only have to change it in one place.

padx = 10
pady = 10
Button(...).pack(padx=padx, pady=pady)

Of course, you can also define your own pack command that automatically applies whatever value you want each time it is called.

There are almost certainly better ways to solve your actual problem, but for the contrived example in the question the best you can do is use the padx and pady parameters in each call to pack().

Answered By: Bryan Oakley

You can do the following if the widgets are in a frame or the main tk window:

for child in frame_name.winfo_children():
    child.grid_configure(padx=10, pady=10)
Answered By: briarfox
def pack_configure_recursive(widget, **kwargs):
    stack = list(widget.winfo_children())
    while stack:
        descendent = stack.pop()
        stack.extend(descendent.winfo_children())
        descendent.pack_configure(**kwargs)

...

pack_configure_recursive(window, padx=10, pady=10)
Answered By: Brent

You could subclass Button and redefine the pack() method:

import tkinter as tk
from tkinter import ttk

class MyButton(ttk.Button):
    def pack(self, *args, **kwargs):
        super().pack(padx=10, pady=10, *args, **kwargs)

root=tk.Tk()
MyButton(text="Hello").pack()
MyButton(text="World").pack()
root.mainloop()
Answered By: Franz Fankhauser
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.