in reply to Change button color with Tk

G'day PerlCowboy,

All (I can't think of any exceptions off the top of my head) Tk widget options start with a "-". See your first post here for a plethora of examples.

All widget documentation is laid out in much the same manner. Looking at Tk::Button, you'll see Standard Options followed by Widget-Specific Options.

The Standard Options are just a list. Their details can be found in Tk::options. At the start of that page, you'll find the cget() and configure() methods: these are what you use to query and change options (both Standard and Widget-Specific ones).

It's unclear precisely what you want to do. If you just want to change the default background colour for your GUI when it's first presented, then ++roboticus is quite correct, you don't include them in a sub; instead, you'll want code like this:

$parent->Button( -text => '...', -background => '...', -command => ... )

If, however, you want a colour to change in response to an event (e.g. a button press), then you will want code in a sub, but using the configure() method I indicated above.

— Ken

Replies are listed 'Best First'.
Re^2: Change button color with Tk
by PerlCowboy (Novice) on Nov 02, 2017 at 19:23 UTC
    I have some working code now, but my buttons are each a unique name. They are $button1 through $button28. Here's the code that works and the sub for the first button:
    my $button1 = $mw->Button(-text => "18-Letters", -command => sub {print OUTFILE "18L\n"}, -command => \&change)->pack(-side => "top"); sub change { $button1->configure(-background=>"yellow") }
    Aside from coding a sub for each button, could I use a if then to configure for an array? The goal is to change the color of the button once it is pressed.
    my @btn = $button1-$button28;
      Hello PerlCowboy,

      you can use a brutal method like storing all buttons into an hash:

      my $mw = MainWindow->new; my %buttons; for (1..9){ $buttons{$_} = $mw->Button(-text=>"Button $_",-command=>[\& +colorize,$_])->pack; } MainLoop; sub colorize{ $buttons{$_[0]}->configure(-bg=>'yellow'); print $buttons{$_[0]}->cget('-text')," button is yellow n +ow\n"; }

      Or you can use Canvas tagging facility to select the current one

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.