问题
- I want to know what's the exact equation for calculating the widget's fit size.
I want to apply that knowledge to dynamically resizing the font of a widget's text, based on the widget's size.
回答1:
Tk GUIs usually work the other way round; the widgets reshape to accommodate their content plus whatever margin and border space is defined. (In Ttk widgets, the style specifies many of those values.) That general requested size is then fed as a suggestion into the geometry management engine. What size a widget actually gets depends on its environment of other widgets as well as what it directly wants, and the rules for that depend on the geometry manager being used; grid
, pack
and place
all have quite different rule engines internally (indeed, grid
is a complex constraint satisfaction solver).
It is easier to work from the other way round. If you know how much space you have, you can use font measure
to work out whether your text in a particular font and size will fit horizontally; with multiple lines (you don't say if this your scenario or not) you need to measure each line individually. Vertically, you usually just get the overall height from font metrics
and multiply by the number of lines of text involved; that's what the font rendering engine effectively does internally anyway.
Here's a helper procedure that shows how to do it in the single line case.
proc findFontForLine {basefont maxX maxY text} {
for {set size 2} {$size < 72} {incr size} {
set testfont [lreplace $basefont 1 1 $size]
if {[font measure $testfont $text] > $maxX} break
if {[font metrics $testfont -linespace] > $maxY} break
set font $testfont
}
if {[info exists font]} {
return $font
}
error "could not find reasonable matching font"
}
set sample "This is some sample text"
set maxX 120
set maxY 30
set font [findFontForLine {Arial 5 bold} $maxX $maxY $sample]
puts "Chosen font is '$font'"
My system prints Chosen font is 'Arial 9 bold'
when I run the code, but fonts and displays can be subtly different so your mileage may well vary.
来源:https://stackoverflow.com/questions/46982863/how-does-tk-calculate-widget-size