tcltk-toolkit

How to align labels to the left and allow resizing in TCL/TK


I want to vertically stack a set of labels, and I would like them to be aligned to the left.

I have tried this:

#!/usr/bin/env tclsh

package require Tk

# Initialize global counter
set widgetCounter 0

# Procedure to generate a unique ID
proc widgetId {prefix} {
    global widgetCounter
    set uniqueId "${prefix}${widgetCounter}"
    incr widgetCounter
    return $uniqueId
}
proc labelId {} { return [widgetId ".lbl"] }
proc sepId {} { return [widgetId ".sep"] }
proc frameId {} { return [widgetId ".frame"] }

# Main GUI Layout
wm title . "WINDOW TITLE"

# 1. HEADER

set l [labelId]
label $l -text "LABEL 1 FOO THIS IS A HEADER" -justify left -fg white -bg darkred -padx 5 -pady 5 
pack $l -side top -anchor w -fill x 

set l [labelId]
label $l -text "ANOTHER LABEL" -justify left -bg blue -padx 5 -pady 5 
pack $l -side top -anchor w -fill x 

set s [sepId]
ttk::separator $s -orient horizontal
pack $s -side top -anchor w -fill x

# Start the application
tkwait window .

However, the result is that the text is not aligned to the left. It is my understanding that the labels are being expanded horizontally though:

Sample program without resizing Sample program after resizing


Solution

  • You need to pass -anchor w to the label function, pack anchor and label anchor are different. Also justify only comes into play when you have >1 line.