How do I use Tkinter to create line-wrapped text that fills the width of the window?

python, tkinter

Solution

`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`.

Problem

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.

Original source