How to set width of widget in Tkinter with a widget inside?

  python, python-3.x, tkinter

In the code I am writing, I create some frames and put them in place as in the example. The hierarchyframe has a set width of 260. When I put in a label with width less than that of the frame, the frame’s width diminishes to that of the label.

The code is below:

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Application")
root.geometry("1200x1000")

s=ttk.Style()
s.configure('TFrame', background='gray')
s.configure('windowframes.TFrame', background='darkgray')

mainframe = ttk.Frame(root, padding="2 2 2 2",height=300)
mainframe.grid(column=0, row=0, sticky=(N,E,S,W))

toolframe = ttk.Frame(mainframe,height=60,style='windowframes.TFrame')
toolframe.grid(column=0, row=0, columnspan=2,sticky=(N,S,E,W), padx=2, pady=2)

hierarchyframe = ttk.Frame(mainframe,width=260,style='windowframes.TFrame')
hierarchyframe.grid(column=0, row=1, rowspan=2, sticky=(N,S,E,W), padx=2, pady=2)
label = Label(hierarchyframe,text="sample")
label.grid(column=0, row=0)

graphicframe = ttk.Frame(mainframe,style='windowframes.TFrame')
graphicframe.grid(column=1, row=1, sticky=(N,S,E,W), padx=2, pady=2)

fileframe = ttk.Frame(mainframe,height=360,style='windowframes.TFrame')
fileframe.grid(column=1, row=2, sticky=(N,S,E,W), padx=2, pady=2)

mainframe.columnconfigure(1,weight=1)
mainframe.rowconfigure(1,weight=1)

root.columnconfigure(0,weight=1)
root.rowconfigure(0,weight=1)

root.mainloop()

The styles are there so you can see the outline of the frames.

Source: Python-3x Questions

One Reply to “How to set width of widget in Tkinter with a widget inside?”

  • I think using parent.pack_propagate(False) will prevent parent’s children from modifying its dimensions. I haven’t done it but I saw it in another query.

LEAVE A COMMENT