简体   繁体   English

如何在 window 或 Tkinter 中设置所有小部件的填充

[英]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.我创建了一个带有两个按钮的 window 并设置了它们的填充。

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.我想从pack()中删除padxpady参数并获得相同的结果。 How can I do this?我怎样才能做到这一点?

You can do the following if the widgets are in a frame or the main tk window:如果小部件位于框架或主tk窗口中,您可以执行以下操作:

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 .没有定义pack的 padx 和 pady 值的全局配置,以消除在调用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.当然,您也可以定义自己的pack命令,每次调用它时都会自动应用您想要的任何值。

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() .几乎肯定有更好的方法来解决您的实际问题,但对于问题中的人为示例,您能做的最好的事情是在每次调用pack()使用padxpady参数。

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:您可以子类化 Button 并重新定义 pack() 方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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