Friday, February 18, 2011

perl/tk mega-widget configuration

perldoc Tk::ConfigSpec says if where is set to SELF then "apply configure to the core widget" but it doesn't explain how to make it work. I started with a skeleton widget:
package Tk::Test;

use strict;
use warnings;

use base 'Tk::Frame';
Tk::Widget->Construct('Test');

sub ClassInit {
    my ($class,$mw) = @_;
    $class->SUPER::ClassInit($mw);
}

sub Populate {
    my ($self, $args) = @_;

    $self->SUPER::Populate($args);

    $self->ConfigSpecs(
        -xxx    => [ 'SELF', 'xxx', 'Xxx', 'x' ],
    );
}

1;
But when I created one, setting option -xxx, I got the following error:

Tk::Error: Can't set -xxx to `XX' for Tk::Test=HASH(0x93d5420): unknown option "-xxx" at /usr/lib/perl5/Tk/Configure.pm line 47.
Eventually I figured out that I need a configure subroutine in my widget. It gets called after Populate has run, passed the -xxx option and its value. My initial widget was inheriting its configure subroutine from Tk::Frame and that configure didn't accept the -xxx option (and why wouldn't it).

I added a configure subroutine...

package Tk::Test;

use strict;
use warnings;
use Data::Dumper;

use base 'Tk::Frame';
Tk::Widget->Construct('Test');

sub ClassInit {
    my ($class,$mw) = @_;
    $class->SUPER::ClassInit($mw);
}

sub Populate {
    my ($self, $args) = @_;

    $self->SUPER::Populate($args);

    $self->ConfigSpecs(
        -xxx    => [ 'SELF', 'xxx', 'Xxx', 'x' ],
    );
}

sub configure {
    my ($self, @args) = @_;

    print "configure: " . Dumper(\@args);
}

1;
With this, the error was gone. Now all I have to do is learn how to write a configure sub properly.

No comments:

Labels