Search code examples
pythontkinter

Python - Understanding TKInter Frames


I’m trying to understand how the Notebook and Frames work in Python.

As far as I understand, if I want a tabbed interface, I create a Notebook widget and add Frame widgets. Here is a simple working sample:

import tkinter
from tkinter import ttk

#   Main Window
window = tkinter.Tk()

#   Notebook
notebook = ttk.Notebook(window)
notebook.pack(expand=True)

#   Frames
apple = ttk.Frame(notebook)
notebook.add(apple, text='Apple')
alabel = ttk.Label(apple, text='Apples')
alabel.pack()

banana = ttk.Frame(notebook)
notebook.add(banana, text='Banana')
blabel = ttk.Label(banana, text='Bananas')
blabel.pack()

tkinter.mainloop()

Any document I can find states that the Frame widget requires a parent, which is the notebook variable above. However:

  • If I leave the constructor empty, it woks just as well.
  • It seems to be redundant if I then add it to the frame later.

I can’t find anything on the Internet other than the syntax which always includes the parent, and examples. The question is, what is the point of the parent parameter in the Frame constructor?

Python 3.12 on a a Macintosh, if that’s helpful.


Solution

  • Tkinter has this weird feature called default root and is source of hideous bugs in some code environments.

    You can see that in BaseWidget._setup

    It is good practice to explicitly reference the parent. Not just because the children gets destroyed with the parent but it's also sometimes required, for the drawing engine, so that the child stays in the parent proportions and do not overlap any borders.