Tkinter Python, is it possible to lock a Frame's size despite the widget within. Specifially Text widgets

83 views Asked by At

I am trying to size some Frames and then pack Text widgets into them. Maybe I am missing something. Firstly is there a proper way to have the Text widget "inherit" its size from the Frame? I have tried this

import tkinter as tk

window = tk.Tk()

f = tk.Frame(width=100, height=50, relief="raised", borderwidth=2)
f.pack()

t = tk.Text(master=f)
t.pack()

window.mainloop()

and the Text's default size overwrites the Frame's size. So I tried to change it to

...
t = tk.Text(master=f, width=100, height=50)
...

and the size is wildly different, which I realize is because the height and width for Text is the character size. So I did some math and got:

...
t = tk.Text(master=f, width=12, height=6)
...

So my real question is, is there a way to pack Text into a Frame and set its size via pixels rather than character? Or to lock the size of the Frame regardless of the Text within? For my purposes I only ever need one widget in the Frame for the most part, but essentially what I'd like to be able to do it size a bunch of Frames and pack widgets into them, maybe their is a better way to do this. Any thoughts are appreciated

1

There are 1 answers

2
Bryan Oakley On

So my real question is, is there a way to pack Text into a Frame and set its size via pixels rather than character?

No, you cannot set the size of the text widget in pixels. However, you tell it to fill the frame, and then tell the frame not to let the children determine its size. Since you're using pack, you would use pack_propagate. This will allow you to set the size of the frame in pixels.

f = tk.Frame(root, width=100, height=100)
t = tk.Text(f)
f.pack_propagate(False)
t.pack(fill="both", expand=True)