epeleg epeleg - 3 years ago 255
Python Question

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:
enter image description here

The yellow frame makes sense and is what I expected.
The same goes for frameA (green) and 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.

It would just seem that rely of frameB keeps being placed w.r.t mainframe or root regardless of the root parameter I use for the instantiation of frameB or the said in_ parameter.

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

What am I doing wrong? or (worse) miss-understanding ?

Answer Source

pack(), grid(), and place() return None, therefore, assigning frameA = Frame(bla bla).place(bla), is assigning None to 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download