bcarroll has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to figure out how to get the width and height of a Tk::Button widget, but I can't figure this one out... Here is an example(the widgets width and height are always 0):
use warnings; use strict; use Tk; my $mw = tkinit(); my $button = $mw->Button(-text => 'Button')->pack(); $button->bind('<ButtonPress-1>', \&buttonPress); $mw->MainLoop(); sub buttonPress{ print 'RootX:' . $button->rootx . "\n"; print 'RootY:' . $button->rooty . "\n"; print 'Width:' . $button->cget(-width) . "\n"; print 'Height:' . $button->cget(-height) . "\n"; }

Replies are listed 'Best First'.
Re: How to get the width/height of a Tk::Button widget?
by Khen1950fx (Canon) on Feb 06, 2012 at 16:58 UTC
    Your code works for me. I added state, text, width and height.
    #!/usr/bin/perl -l use strict; use warnings; use Tk; my $mw = tkinit(); my $button = $mw->Button( -text => 'Button', -width => 5, -height => 1, -command => sub { exit } )->pack(); $button->bind( '<ButtonPress-1>', \&buttonPress ); $mw->MainLoop(); sub buttonPress { my @queries = ( 'RootX: ' . $button->rootx, 'RootY: ' . $button->rooty, 'State: ' . $button->cget('-state'), 'Text: ' . $button->cget('-text'), 'Width: ' . $button->cget('-width'), 'Height:' . $button->cget('-height'), ); foreach my $query( @queries ) { print $query; } }
Re: How to get the width/height of a Tk::Button widget?
by kcott (Archbishop) on Feb 06, 2012 at 18:02 UTC

    $widget->cget() returns the configured value which may be:

    • the widget's default (Tk::Button has both -height and -width set to 0)
    • a value used when creating the widget (see Khen1950fx's post above with the values 1 and 5)
    • a new value set with $widget->configure()

    Try using $widget->height() and $widget->width(). Both give the value in pixels. See Tk::Widget for details.

    -- Ken

      Thanks for all the responses! $button->width() and $button->height() worked for me! (ActivePerl 5.10 on Windows XP)
Re: How to get the width/height of a Tk::Button widget?
by thundergnat (Deacon) on Feb 06, 2012 at 15:54 UTC

    That's odd, and certainly seems like it should work. <speculation>It probably is a side effect of Button treating width and height as multiples of font character dimensions rather than pixel dimensions.</speculation>

    You can still get at the pixel dimensions by checking the widget geometry though.

    use warnings; use strict; use Tk; my $mw = tkinit(); my $button = $mw->Button( -text => 'Button', -command => \&buttonPress )->pack(); $mw->MainLoop(); sub buttonPress{ print 'RootX:' . $button->rootx . "\n"; print 'RootY:' . $button->rooty . "\n"; my ( $width, $height, $deltax, $deltay ) = split /[+x]/, $button-> +geometry; print join "\n", "Height: $height", "Width: $width", "Delta X (from root): $deltax", "Delta Y (from root): $deltay"; }