pythontkinter

TKInter widget not appearing on form


I’m having trouble working out why a widget doesn’t appear on my tkinter form.

Here is what I’m doint:

Any widgets I create before the notebook and frame don’t appear, even though I don’t add them till after they’ve been created.

Here is some sample code:

form = tkinter.Tk()

label1 = tkinter.ttk.Label(form, text='Test Label 1')   #   This one doesn’t appear

notebook = tkinter.ttk.Notebook(form)
notebook.pack(expand=True)
mainframe = tkinter.ttk.Frame(notebook, padding='13 3 12 12')
notebook.add(mainframe, text='Test Page')

label2 = tkinter.ttk.Label(form, text='Test Label 2')   #   This one works
entry = tkinter.ttk.Entry(form)

label1.grid(in_=mainframe, row=1, column=1)
label2.grid(in_=mainframe, row=2, column=1)
entry.grid(in_=mainframe, row=3, column=1)

form.mainloop()

Note that label doesn’t appear even though there is a space for it. If I print(id(form)) before and after creating the notebook and frame, they are the same, so it’s not as if the form itself has changed.

Where has that first widget gone to and how can I get it to appear?


Solution

  • The behavior has to do with stacking order. Widgets created before the notebook are lower in the stacking order. In effect it is behind the notebook. You'll you correctly observed that a row has been allocated for the widget, but since it's behind the notebook it isn't visible.

    You can make it appear by calling lift on the widget to raise the stacking order:

    label1.lift()
    

    screenshot