0

It is only a simple question but shouldn't a label stay inside of it's nested frame when you use sticky ? In my code it only stays in the parent frame. If it is normal do you have a solution ?

I have tried looking the documentation but I didn't find anything which could help.

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Tk test")
root.geometry("800x800")

frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1)
frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200").grid(row=0, column=0, rowspan=1, columnspan=1)
label_1 = ttk.Label(frame_2, text="Text").grid(row=0, column=0, sticky="N, E")

root.mainloop()

Expected result : The label stays inside of it's frame which is nested inside the parent frame. Actual results : It only stays inside the parent frame

BrockenDuck
  • 220
  • 2
  • 14

2 Answers2

1

The .grid(...) function returns None. Therefore, when you do

frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400").grid(row=0, column=0, rowspan=1, columnspan=1)

you assign None to frame_1. And the same goes for frame_2 and label_1.

Because frame_1 == None, calling ttk.Frame(frame_1, ...) is actually the same as ttk.Frame(None, ...). Therefore, you're not passing a master, which defaults to having the root window as the master. Again, the same goes for the creation of label_1.

The fix is to split the creation and placement of the widgets to two separate lines:

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Tk test")
root.geometry("800x800")

frame_1 = ttk.Frame(root, relief="sunken", height="400", width="400")
frame_1.grid(row=0, column=0, rowspan=1, columnspan=1)
frame_2 = ttk.Frame(frame_1, relief="sunken", height="200", width="200")
frame_2.grid(row=0, column=0, rowspan=1, columnspan=1)
label_1 = ttk.Label(frame_2, text="Text")
label_1.grid(row=0, column=0, sticky="N, E")

root.mainloop()
fhdrsdg
  • 10,297
  • 2
  • 41
  • 62
  • I normally do it in two separate lines too. But what is the difference between doing it on the same line and in two separate lines ? – BrockenDuck Apr 09 '19 at 14:37
  • When you chain functions, python will return the value of the last function. For example, `' '.join(['a', 'b'])` returns `'a b'`, but`' '.join(['a', 'b']).split()` returns `['a', 'b']`. In the same way, `ttk.Frame(...)` returns a Frame object, but `ttk.Frame(...).grid(...)` returns `None`, because that is the return value of `grid`. Also see [this answer](https://stackoverflow.com/a/1101765/3714930). – fhdrsdg Apr 09 '19 at 14:48
-2

add .pack() at the end of each line where you define frame_1, frame_2 and label_1