Parent/master vs. in_ in tkinter

南笙酒味 提交于 2020-01-24 06:02:10

问题


Examine the following code:

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

Taken from: How do I center a frame within a frame in Tkinter?

One of the comments there says "The root window is the default when a widget doesn't explicitly specify a parent" and also " In this case f1 is being managed by the root window and f2 is being managed by f1 (because of the in_ parameter)."

What is the difference between the hierarchy created by the master parameter used in the instantiation of new widgets and the hierarchy created by the the in_ prameter used in the .place layout manager?

Why is f2 not being created as a child of f1? (and would it change anything?)


回答1:


What is the difference between the hierarchy created by the master parameter used in the instantiation of new widgets and the hierarchy created by the the in_ prameter used in the .place layout manager?

The simple answer is that there is no hierarchy created by the in_ parameter. The only hierarchy is the parent/child relationship when the widget is created.

The in_ parameter merely identifies a widget into which the other widget should be placed. It tells tkinter "make this child's placement relative to this other widget".

Why is f2 not being created as a child of f1? (and would it change anything?)

It's not being created as a child because you didn't tell it to be a child. You didn't specify a parent, so tkinter uses the root window as the parent.

Would it change anything if you did? Not in this specific case. If f1 did not fill the whole window, or filled it asymmetrically, f2 would appear centered in f1 but not centered in the window as a whole.




回答2:


My lack of understanding seems to have been the result of a problem in my code for which I got an answer here: tkinter placement of widgets

Getting rid of the issue describe there I can now see that:

Master/parent: defines a bounding area limiting the rendering of its child widgets

in_: sets the widget on which the positioning of the in_(cluded) widget would be based



来源:https://stackoverflow.com/questions/46521814/parent-master-vs-in-in-tkinter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!