简体   繁体   中英

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

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?

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)

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() .

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM