tkinter pack 方法的 "fill" 和 "expand" 选项之间的区别

Difference between "fill" and "expand" options for tkinter pack method

我知道这是一个太琐碎的问题,但我是 python 的新手,而且我刚刚开始使用 tkinter 模块。其实我到处都查过了,都没有找到满意的答案。我发现了以下内容:

fill option: it determines whether to use up more space or keep "one's own" dimensions.

expand option: it deals with the expansion of parent widget.

问题是这两个声音或多或少相同。我什至通过在 fill 的 4 个值和 expand 的 2 个值之间切换来尝试了一些示例,但在 2 或 3 个案例中收到或多或少相同的输出,因此我有这个查询。在这方面的任何帮助将不胜感激。提前致谢!

来自effbot

The fill option tells the manager that the widget wants fill the entire space assigned to it. The value controls how to fill the space; BOTH means that the widget should expand both horizontally and vertically, X means that it should expand only horizontally, and Y means that it should expand only vertically.

The expand option tells the manager to assign additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the expand option set to a non-zero value.

所以 fill 告诉小部件在指定的方向上增长到尽可能多的 space 可用,expand 告诉主人采取任何 space未分配给任何小部件并将其分发给具有 non-zero expand 值的所有小部件。

当 运行 这个例子时,差异变得明显:

import Tkinter as tk

root = tk.Tk()
root.geometry('200x200+200+200')

tk.Label(root, text='Label', bg='green').pack(expand=1, fill=tk.Y)
tk.Label(root, text='Label2', bg='red').pack(fill=tk.BOTH)

root.mainloop()

你可以看到带有 expand=1 的标签被分配了尽可能多的 space,但只在指定的方向 Y 上占据它。 fill=tk.BOTH 的标签双向扩展,但可用的 space 较少。

我已经完成了反复试验。这是一个概述:

import tkinter as tk

root = tk.Tk()
root.geometry()

for e, expand in enumerate([False, True]):
    for f, fill in enumerate([None, tk.X, tk.Y, tk.BOTH]):
        for s, side in enumerate([tk.TOP, tk.LEFT, tk.BOTTOM, tk.RIGHT]):
            position = '+{}+{}'.format(s * 205 + 100 + e * 820, f * 235 + 100)
            win = tk.Toplevel(root)
            win.geometry('200x200'+position)
            text = str("side='{}'\nfill='{}'\nexpand={}".format(side, fill, str(expand)))
            tk.Label(win, text=text, bg=['#FF5555', '#55FF55'][e]).pack(side=side, fill=fill, expand=expand)
                
root.mainloop()

我也是一个努力理解这些选项如何协同工作的人。

谢天谢地,在Ronald的视觉解释下终于明白了。

所以我做了一些程序来模拟 pack 的工作原理。
https://github.com/thom-jp/tkinter_pack_simulator

这是 运行 程序的图像: