简体   繁体   English

tkinter小部件的放置

[英]tkinter placement of widgets

Consider the following simple code: 考虑以下简单代码:

    from tkinter import *

    mainFrame = Frame(parent, bd=5, bg="yellow").pack(expand=True,fill=BOTH)

    frameA = Frame(mainFrame, bd=5, bg="green").place(anchor=NW, relx=0, rely=0 , relwidth=1.0, height=40)
    my_label = Label(mainFrame, text="Hello world ", bg="red").place(in_=frameA, relx=0, anchor=NW, rely=0, relwidth=0.5)

    frameB = Frame(frameA, bd=5, bg="gold").place(in_=frameA , anchor=N, relx=0.5, rely=0.8, width=30, height=50)

The result looks like this: 结果看起来像这样: 在此处输入图片说明

The yellow frame makes sense and is what I expected. 黄色框很有意义,这正是我所期望的。 The same goes for frameA (green) and my_label. frameA(绿色)和my_label也是如此。

However, frameB refuses to do what I expect, originally I have rely=1.0 for its place command and I was expecing it's N (top center edge) to be placed at the horizontal midpoint of the bottom (1.0*height) of the green frame which I have set up to be both its parent and used as it .place() command _in parameter. 但是,frameB拒绝执行我期望的操作,起初我将其== 1.0作为其place命令,并且期望将其N(顶部中央边缘)放置在绿色框架底部(1.0 *高度)的水平中点我已将其设置为它的父对象,并将其用作.place()命令_in参数。

It would just seem that rely of frameB keeps being placed wrt mainframe or root regardless of the root parameter I use for the instantiation of frameB or the said in_ parameter. 似乎无论我在frameB实例化中使用的根参数还是所说的in_参数,frameB的依赖关系始终放置在大型机或根目录中。

I know that I can use .pack(), but I am trying to figure out the behavior of .place() so please don't send me to use neither .pack() nor .grid(). 我知道我可以使用.pack(),但是我试图弄清楚.place()的行为,所以请不要让我不要使用.pack()和.grid()。

What am I doing wrong? 我究竟做错了什么? or (worse) miss-understanding ? 还是(更糟糕的)误会?

pack() , grid() , and place() return None , therefore, assigning frameA = Frame(bla bla).place(bla) , is assigning None to frameA pack()grid()place()返回None ,因此,分配frameA = Frame(bla bla).place(bla) ,将None分配给frameA

You will need to do this in two steps to get what you need: 您将需要分两步执行此操作以获取所需的内容:

  • First create the widget. 首先创建小部件。
  • Second place it. 第二名。

Something along these lines: 遵循以下原则:

mainFrame = Frame(parent, bd=5, bg="yellow")
mainFrame.pack(expand=True,fill=BOTH)

frameA = Frame(mainFrame, bd=5, bg="green")
frameA.place(anchor=NW, relx=0, rely=0 , relwidth=1.0, height=40)

my_label = Label(mainFrame, text="Hello world ", bg="red")
my_label.place(in_=frameA, relx=0, anchor=NW, rely=0, relwidth=0.5)

frameB = Frame(frameA, bd=5, bg="gold")
frameB.place(in_=frameA , anchor=N, relx=0.5, rely=0.8, width=30, height=50)

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

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