Search code examples
tcltk-toolkit

Getting actual dimensions of label tcl/tk widget


I try to display some data stored in array with a table-like view. To do this, I loop through the array and retrieve relevant data into labels which are then used as "table cells". Each "table row" is run as frame. Now I need to make the "cells" of certain "column" have same width. The idea is to retrieve the width of the widest "cell" in the column and apply it to all the other "cells" there. The amount of data to display is up to couple of thousands rows so I am not concerned about performance issues (although will be happy to see better solutions if possible). The problem is how to get the actual width of each label? Using cget option returns "0". Artificial predicting the max width is not an option :( Below is the simplified code:

set cnt 0;
set maxWidth 0;
    
foreach {rName rData} [array get SourceArray] { 
        frame .row_${cnt};
        label .row_${cnt}.rName -text $rName;
        label .row_${cnt}.rData -text $rData;

        grid .row_${cnt}.rName  -row $cnt -column 0;
        grid .row_${cnt}.rData  -row $cnt -column 1;

        pack .row_${cnt} -in .ParentFrame -fill x; 

        if {[.row_${cnt}.rName cget -width] > $maxWidth} {set maxWidth [.row_${cnt}.rName cget -width]}
    
        incr cnt 1;
}

# Run "for" loop to further apply the $maxWidth value to all the labels in the "column"

Solution

  • The actual dimensions of a widget are available through winfo width and winfo height, but those are set to dummy values immediately after widget creation, and only become correct after the widget has drawn itself. (Technically, it's after the final <Configure> event is delivered before the first <Map> event.) Before then, you can only usefully use winfo reqwidth/winfo reqheight to get the requested width and height; that's all you really know until the window manager and nested geometry managers finish their negotiations. A widget may get either more or less space than it asked for, and the two dimensions are mostly independent (though some layouts might make that less so, of course).