-3

The Tk documentation says (last section) that nested layouts can be achieved using tk.frame. The following small example is not working as expected, instead of:

enter image description here

import tkinter as tk

window = tk.Tk()
window.geometry('250x100')

# first level, window as parent
tk.Label(window, text='Choose file:').grid(row=0, column=0, sticky=tk.W)
tk.Button(window, text='Browse ...').grid(row=1, column=0, sticky=tk.W)
fr = tk.Frame(window).grid(row=2, column=0, sticky=tk.W)

# nested, frame as parent
tk.Entry(fr).grid(row=0, column=0, sticky=tk.W)
tk.Entry(fr).grid(row=0, column=1, sticky=tk.W)

tk.mainloop()

it produces:

enter image description here

The real UI is much more complex, so I really want to use nested grids instead of one grid with multiple columns.

APhillips
  • 1,175
  • 9
  • 17
Mikhail Poda
  • 5,742
  • 3
  • 39
  • 52
  • 1
    Read [AttributeError: NoneType object has no attribute ...](https://stackoverflow.com/a/1101765/7414759), your `fr` is `None` therefore the parent is `root`. – stovfl Jan 07 '20 at 19:24
  • 1
    It would have taken just a few seconds to verify that `fr` is not set to what you think it is. – Bryan Oakley Jan 07 '20 at 19:27
  • Bryan - you are right, I am just too used to statically typed languages. But why Python is not throwing an error in such case? – Mikhail Poda Jan 07 '20 at 19:29
  • @Mikhail: because there is no error to report. It's perfectly valid to do what you did, it's just that what you expect to happen and what is documented to happen are two different things. – Bryan Oakley Jan 07 '20 at 20:46

1 Answers1

1

AFAIK, tkinter does not produce intuitive results if you create an object and grid at once. This should give you the same result with the documentation:

import tkinter as tk

window = tk.Tk()
window.geometry('250x100')

# first level, window as parent
tk.Button(window, text='Browse ...').grid(row=1, column=0, sticky=tk.W)
tk.Label(window, text='Choose file:').grid(row=0, column=0, sticky=tk.W)
fr = tk.Frame(window)
fr.grid(row=2, column=0, sticky=tk.W)

# nested, frame as parent
entry1 = tk.Entry(fr)
entry1.grid(row=0, column=0, sticky=tk.W)
entry2 = tk.Entry(fr)
entry2.grid(row=0, column=1, sticky=tk.W)

tk.mainloop()
isydmr
  • 649
  • 7
  • 16
  • It's not so much that "it doesn't produce good results", it's that it doesn't produce _intuitive_ results. – Bryan Oakley Jan 07 '20 at 19:26
  • Oh, I got it - `fr` was not the frame object. I wonder why python accepts such code without an error – Mikhail Poda Jan 07 '20 at 19:26
  • ***"tkinter does not produce good results if you create an object and grid at once."***: Did you have any reference about this. – stovfl Jan 07 '20 at 19:26
  • @Mikhail ***"I wonder why python accepts such code without an error"***: It's the default, you can change it by calling `tk.NoDefaultRoot()` – stovfl Jan 07 '20 at 19:30