Reputation: 189
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()
Upvotes: 0
Views: 672
Reputation: 386342
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.
Upvotes: 1