use Tk; use Tk::Font; my $mw = MainWindow->new; my $label = $mw->Label( -text => "Hello", -font => "Times 12" )->pack(-expand => 1, -fill => 'both'); $label->bind('', \&ResizeText); MainLoop; sub ResizeText { my ($widget) = @_; $widget->bind('', ""); ## Check to see if the font is "registered" ## so that we can use Tk::Font methods reliably my $knownFont = 0; my $font = $widget->cget('-font'); foreach my $f ($widget->fontNames()) { if ($$f eq $$font) { $knownFont = 1; last; } } ## If we're dealing with an unregistered font we ## could run into problems, so it's safest to create ## a new font based off the unregistered fonts attrs. ## Otherwise, reuse the existing font rather than ## recreating a new one. unless($knownFont) { $font = $widget->Font($font->actual); $widget->configure(-font => $font); } my $widthF = $font->measure($widget->cget('-text')); my $heightF = $font->metrics('-linespace'); my $xRatio = $widget->width / $widthF; my $yRatio = $widget->height / $heightF; my $minRatio = $xRatio < $yRatio ? $xRatio : $yRatio; my $fontSize = $font->actual('-size'); $font->configure(-size => ($minRatio * $fontSize)); $widget->update; $widget->bind('', \&ResizeText); }