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

Configure default widget options in Tk

Is there a way to configure the default options that a particular type of widget will use when initialized? I have been setting them in a hash and adding it to the parameter list when calling the widget's constructor. It seems that there should be a better way built into Tk, but I've been unable to find it.

# this is what I'm doing: my %button_options = ( -font => '{Arial} 10 {bold}', -padx => 2, -pady => 2, ); my $button1 = $mw->Button( %button_options, -text => 'foo', -command => \&foo, ); my $button2 = $mw->Button( %button_options, -text => 'bar', -command => \&bar, ); # I would like to do it something like this: setDefaults ( -widget => 'Button', -font => '{Arial} 10 {bold}', -padx => 2, -pady => 2, ); my $button1 = $mw->Button( -text => 'foo', -command => \&foo, ); my $button2 = $mw->Button( -text => 'bar', -command => \&bar, );

Replies are listed 'Best First'.
Re: Configure default widget options in Tk
by zentara (Cardinal) on Jan 19, 2009 at 17:56 UTC
    You might want to checkout optionAdd and "perldoc Tk::options".
    #!/usr/bin/perl -w use strict; use Tk; my $mw=tkinit; $mw->optionAdd("*background"=>'lightblue','userDefault'); $mw->Listbox->pack->insert(0,qw/a listbox/); $mw->Text->pack->insert('1.0','text widget'); $mw->Entry->pack->insert(0,'entry widget'); MainLoop;

    I'm not really a human, but I play one on earth Remember How Lucky You Are

      Thanks zentara. Actually I found optionAdd under "perldoc Tk:option" (not plural). Usage wasn't exactly intuitive or clear, but I came up with the following which does what I want - sets default values for buttons without affecting any other type of widget.

      $mw->optionAdd('*Button.font', '{Arial} 14 {bold}', 'userDefault'); $mw->optionAdd('*Button.padX', '2', 'userDefault'); $mw->optionAdd('*Button.padY', '2', 'userDefault');