29

The Label widget doesn't line-wrap. The Message widget will line-wrap text, but forces it to be roughly square. Here's an example:

from Tkinter import *

root = Tk()
root.title("hello")

Message(root, text=48*'xxxxx ').grid(row=0, column=0, columnspan=3)

Label(root, text='Name:').grid(row=1, column=0)
Entry(root, width=50).grid(row=1, column=1)
Button(root, text="?").grid(row=1, column=2)

Button(root, text="Left").grid(row=2, column=0)
Button(root, text="Center").grid(row=2, column=1)
Button(root, text="Right").grid(row=2, column=2)

root.mainloop()

I know that I can use aspect=700 to change the shape, but hard-coding numbers like that is what I'm trying to avoid.

martineau
  • 119,623
  • 25
  • 170
  • 301
samwyse
  • 2,760
  • 1
  • 27
  • 38

4 Answers4

57

The Tkinter Label widget does wrap. It is just that the default setting is no wrapping. To get the text on one to wrap set the wraplength parameter, the units for this are screen units so try wraplength=50 and adjust as necessary. You will also need to set justify to LEFT, RIGHT, or CENTER.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jim Denney
  • 571
  • 5
  • 2
15
welcomenote = Label(root, text="Your long text", font="helvetica 14", 
wraplength=300, justify="center")
welcomenote.pack()
Uduak Akpan
  • 151
  • 1
  • 2
9

wraplength is indeed the correct answer, but it's a fixed width. If you have a dynamically sized Label you will need to update wraplength as it is resized. You can do this by binding the <Configure> event:

label = tk.Label(root, text="My long text")
label.bind('<Configure>', lambda e: label.config(wraplength=label.winfo_width()))

In some configurations I do get wrapping that is slightly off, i.e. the text runs slightly off the edge of the Label before wrapping. I haven't figured out whether that's due to the font, any margins/padding, or what is going on. I just worked around this by subtracting a fixed amount from label.winfo_width() before feeding it into wraplength.

rem
  • 1,298
  • 2
  • 9
  • 16
  • 2
    This is a good solution but the implementation may lead to an infinite loop since if calls the view configure on the view configure event. You may want to wrap the label in a Frame superview and bind the event listening to this view instead. – Louis Lac Jan 16 '23 at 14:37
4

Try the following:

tk.Label(root, textvariable=text, wraplength=500).pack()

Here 500 is the amount of pixels before the characters are put to the next line.

ivcubr
  • 1,988
  • 9
  • 20
  • 28
BadBandana
  • 41
  • 2