简体   繁体   English

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

[英]Is it possible to easily center side-stacked frames in a frame in tkinter?

I am faced with the problem to center side-stacked frames in a parent frame. 我面临着将侧面堆叠的框架居中放置在父框架中的问题。 I know how to center a single frame in a frame but I did not find a simple way to do this for several of them. 我知道如何将单个框架居中放置在一个框架中,但是我没有找到一种简单的方法来对其中的几个框架执行此操作。

I get the following window 我得到以下窗口

在此处输入图片说明

from the code below: 从下面的代码:

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

I would like the three square frames to be centered in the green one. 我希望将三个方形框架以绿色为中心。 I had to use tk.LEFT to position them, otherwise they would have been stacked up by default. 我必须使用tk.LEFT定位它们,否则它们将默认堆叠。

In my complete program, the green frame is there to exclusively contain the three square frames. 在我完整的程序中,绿色框在那里专门包含三个正方形框。

What is the most standard way to center the three square frames in the green one? 将三个方形框架居中绿色的最标准方法是什么?

While thinking about furas 's comment I realized that I did not understand the true difference between expand and fill (it is still a bit vague). 在思考furas的评论时,我意识到我不理解expandfill之间的真正区别(仍然有点模糊)。 It is possible to center the three frames by changing the f1.pack() line to: 通过将f1.pack()行更改为:可以将三个框架居中:

f1.pack(side=tk.LEFT, expand=True, fill=None)

The f1 frame is tight around the three square ( fill=None ) ones buts tries to take as much space as possible in all directions ( expand=True ), effectively being centered. f1框架紧紧围绕三个正方形( fill=None ),但是试图在所有方向上都尽可能多地占据空间( expand=True ),有效地居中。 Note that the green background is not visible, the frame being tight around its content. 请注意,绿色背景是不可见的,框架紧紧围绕其内容。

在此处输入图片说明

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

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