label wrapping

MGS - Sometimes I like to have labels that automatically wrap to the width of the window, sort of like a text widget, but without the scrolling (i.e. the whole label text is always visible). It's pretty easy to do (for basic text-only labels):

  label .l -text "A label with a long text string to test auto-wrapping"
  pack  .l -fill x
  bind  .l <Configure> [list %W configure -wraplength %w]

Then resize the toplevel window. You have to make sure that the label is packed/gridded to fill available space.

Of course, this simplified version ignores things like padding and compound images, so here's a more complete example:

  proc label:wrap {W w} {
  
    set px [$W cget -padx]
  
    if { [catch {$W cget -compound} side] } {
      set wl [expr {$w - (2 * $px)}]
    } else {
      switch -- $side {
        left -
        right {
          set image [$W cget -image]
          if { [string length $image] } {
            set iw [image width $image]
          } else {
            set iw 0
          }
          set wl [expr {$w - (3 * $px) - $iw}]
        }
        default {
          set wl [expr {$w - (2 * $px)}]
        }
      }
    }
  
    $W configure -wraplength $wl
  }
  
    pack propagate . 0
    set image [image create photo]
    $image put red -to 0 0 16 16
    label .l \
      -bg white \
      -text "A label with a long text string to test auto-wrapping" \
      -image $image \
      -compound left \
      -anchor w \
      -justify l \
      -padx 10
    pack  .l -fill x
    bind  .l <Configure> [list label:wrap %W %w]

MGS [2003/04/20] - I have combined the above code with that in label selection and created a package which you can find in the Links section at Mark G. Saye.


JNC [2010/06/03] - On TkChat, emiliano came up with this solution which seems to work fine:

    bind $label <Configure> { %W configure -wraplength [expr { %w - 4 }] }

RLE (2011-06-08) There is a crucial bit of information about the above code that was omitted:

The -4 above (as your -9) is crucial. Without it the text becomes invisible for some combinations of text width and ttk::label width.


2011-06-08 clt:wraplength and dynamically-sized widgets