父母/主人与in_ in tkinter

时间:2017-10-02 08:16:46

标签: python tkinter tk

检查以下代码:

import Tkinter as tk

root=tk.Tk()
f1 = tk.Frame(width=200, height=200, background="red")
f2 = tk.Frame(width=100, height=100, background="blue")

f1.pack(fill="both", expand=True, padx=20, pady=20)
f2.place(in_=f1, anchor="c", relx=.5, rely=.5)

root.mainloop()

取自:How do I center a frame within a frame in Tkinter?

其中一条评论显示"The root window is the default when a widget doesn't explicitly specify a parent"以及" In this case f1 is being managed by the root window and f2 is being managed by f1 (because of the in_ parameter)."

在新窗口小部件实例化中使用的主参数创建的层次结构与.place布局管理器中使用的in_参数创建的层次结构之间有什么区别?

为什么不将f2创建为f1的子元素? (它会改变什么吗?)

2 个答案:

答案 0 :(得分:2)

  

在新窗口小部件实例化中使用的主参数创建的层次结构与.place布局管理器中使用的in_参数创建的层次结构之间有什么区别?

简单的答案是in_参数没有创建层次结构。唯一的层次结构是创建窗口小部件时的父/子关系。

in_参数仅标识应放置其他窗口小部件的窗口小部件。它告诉tkinter"使这个孩子的位置相对于其他小部件#34;。

  

为什么不将f2创建为f1的子元素? (它会改变什么吗?)

因为你没有把它当成孩子,所以不是因为孩子而被创造出来的。您没有指定父级,因此tkinter使用根窗口作为父级。

如果你这样做会改变什么吗?不是在这种特定情况下。如果f1没有填满整个窗口,或者不对称填充,f2将显示在f1的中心,但不会整个窗口居中。

答案 1 :(得分:0)

我缺乏理解似乎是我的代码中出现问题的结果,我在这里得到了答案: tkinter placement of widgets

摆脱问题描述我现在可以看到:

主/父:定义限制其子窗口小部件的呈现的边界区域

in_:设置in_(cluded)小部件的定位所基于的小部件