Search code examples
pythonwidgettkintersize

How to prevent Tkinter labelframe size changes when an empty label is inserted


I create a LabelFrame widget. It has a nice size in the beginning:

import Tkinter
form = Tkinter.Tk()

errorArea = Tkinter.LabelFrame(form, text=" Errors ", width=250, height=80)
errorArea.grid(row=2, column=0, columnspan=2, sticky="E", \
             padx=5, pady=0, ipadx=0, ipady=0)

enter image description here

But when I insert an empty string in it, the errorArea widget's size adjusts according to the inserted string:

errorMessage = Tkinter.Label(errorArea, text="")
errorMessage.grid(row=0, column=0, padx=5, pady=2, sticky='W')

enter image description here

How do I give the errorArea widget a fixed size, so that its size won't change according to Lable inserted in it?


Solution

  • That problem always was interesting to me. One way I found to fix it is by using the place method instead of grid:

    import Tkinter
    
    form = Tkinter.Tk()
    
    errorArea = Tkinter.LabelFrame(form, text=" Errors ", width=250, height=80)
    errorArea.grid(row=2, column=0, columnspan=2, sticky="E", \
                 padx=5, pady=0, ipadx=0, ipady=0)
    
    errorMessage = Tkinter.Label(errorArea, text="")
    
    # 1) 'x' and 'y' are the x and y coordinates inside 'errorArea'
    # 2) 'place' uses 'anchor' instead of 'sticky'
    # 3) There is no need for 'padx' and 'pady' with 'place'
    # since you can specify the exact coordinates
    errorMessage.place(x=10, y=10, anchor="w")
    
    form.mainloop()
    

    With this, the label is placed in the window without shrinking the labelframe.