是否可以轻松地将侧面堆叠的框架置于tkinter的框架中?

时间:2014-07-22 10:44:14

标签: python tkinter

我面临的问题是在父框架中居中堆叠的框架。我知道how to center a single frame in a frame但我没有找到一种简单的方法来为其中几个人做这件事。

我得到以下窗口

enter image description here

来自以下代码:

import Tkinter as tk

root = tk.Tk()
root.geometry("200x200")

# main frame
f = tk.Frame(root, background='black')
f.pack(expand=True, fill="both")

# two side-by-side frames inside, they fill up their space
f1 = tk.Frame(f, background='green')
f1.pack(side=tk.LEFT, expand=True, fill="both")
f2 = tk.Frame(f, background='red')
f2.pack(side=tk.LEFT, expand=True, fill="both")

# three fixed-size frames in the left frame above; I would like them to be centered in the frame
tk.Frame(f1, width=20, height=20,  background="orange").pack(side=tk.LEFT, fill=None, expand=False)
tk.Frame(f1, width=20, height=20, background="white").pack(side=tk.LEFT, fill=None, expand=False)
tk.Frame(f1, width=20, height=20, background="gray50").pack(side=tk.LEFT, fill=None, expand=False)

root.mainloop()

我希望三个方框在绿色框架中居中。我不得不使用tk.LEFT来定位它们,否则它们会默认堆叠起来。

在我的完整程序中,绿框只包含三个方框。

将三个方框在绿色方框中居的最标准方法是什么?

1 个答案:

答案 0 :(得分:0)

在考虑furas的评论时,我意识到我不明白expandfill之间的真正区别(它仍然有点模糊)。通过将f1.pack()行更改为:

,可以使三个帧居中
f1.pack(side=tk.LEFT, expand=True, fill=None)

f1框架在三个方格(fill=None)周围很紧,但试图在所有方向(expand=True)占用尽可能多的空间,实际上是居中。请注意,绿色背景不可见,框架内容紧张。

enter image description here