Search code examples
pythontkinterwidgetwidthframe

How can i change frame widget width in python


I'm trying to resize a frame in tkinter, but the width does not change and function winfo_width() returns 1. How can i fix it?

from tkinter import *

root = Tk()
root.geometry('400x300')
Frame = LabelFrame(root, text="Test", width = 200)
Frame.grid(row = 0, column = 0)
label = Label(Frame, text = '').grid(row = 0, column=0)


print(Frame.winfo_width()) #output is 1 instead of 200

root.mainloop()

Solution

  • As the others have pointed out how to set a static size frame using grid_propagate() I will show you how to set up your frame to resize automatically.

    You need to tell the row and column to expand that the frame is in. This is done with columnconfigure() and rowconfigure(). Then you need to tell the frame to stick to all sides with sticky='nsew'. Adding widgets to the frame is no different then any other container. Simply tell the widget to be in the frame.

    One potention issue I see is you are overwriting Frame() on this line: Frame = LabelFrame(root, text="Test", width = 200). This is a good example why you should not use import *. Instead do import tkinter as tk and use the tk. prefix for anything that needs it.

    Example:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry('400x300')
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    frame = tk.LabelFrame(root, text='Test', width=200)
    frame.grid(row=0, column=0, sticky='nsew')
    label = tk.Label(frame, text='label').grid(row=0, column=0)
    root.mainloop()
    

    Results:

    enter image description here

    Update:

    If you do want something static make sure you define both height and width. If you only define one or the other then you will not see the frame in the window.

    For a testable example for a static frame size:

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry('400x300')
    root.rowconfigure(0, weight=1)
    root.columnconfigure(0, weight=1)
    frame = tk.LabelFrame(root, text='Test', height=200, width=200)
    frame.grid(row=0, column=0)
    frame.grid_propagate(False)
    label = tk.Label(frame, text='label').grid(row=0, column=0)
    
    root.mainloop()
    

    Results:

    enter image description here