0

I have a frame and I want it to be a certain size (relative to the root window). When I pack in a label with text big enough to make the label bigger than the frame that contains it, the frame expands. How do I prevent the frame from expanding and make the words that don't fit into one line just go into the next line. I need a solution different than simply adding \n because in my actual project the text is dependant on the users input.

from tkinter import *

root = Tk()
root.geometry("300x300")

f = Frame(root,width=100, height=50, bg="yellow")
f.place(relx=0.5, rely=0.5, anchor=CENTER)

Label(f, text="this is a veeeeeery looooong text").pack(side=LEFT)

root.mainloop()
Enrique Metner
  • 169
  • 1
  • 9

1 Answers1

1

If you want the label to be a fixed size you can specify a size for the label. Tkinter will do its best to honor the requested size. Of course, that means that long text will be chopped off in the label.

Label(f, width=4, text="this is a veeeeeery looooong text").pack(side=LEFT)

With that, the frame will shrink if it's larger than the space required by the label, but it won't grow since the label itself won't grow.

If you want the label to have no effect on the frame at all, you can turn geometry propagation off for the frame. By turning it off, you are telling tkinter to honor the requested size of the frame and not let the size of the children override that.

f.pack_propagate(False)

This is rarely a good idea since tkinter is really good at computing the optimal size, but there are some rare occassions where it is exactly the right thing to do.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks, that's some nice stuff to know. However, I need the whole text to be visible. Like, the frame doesn't have much space on the x-axis but enough on the y-axis which can be used. How can I make a Label which makes the text jump to the next line when there is no more space on the x-axis in the frame? – Enrique Metner Nov 07 '20 at 21:01
  • 1
    @EnriqueMetner: the answer to that is in the tkinter documentation. The `Label` widget has a `wraplength` option. – Bryan Oakley Nov 07 '20 at 22:37