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

Hello Monks,

I searched here for Tk::Tree and did not find a relevant article, CPAN, and O'Reilly ... but the answer is elusive.

I am able to populate a Tk::Tree with a structure, and after some processing, I would like to change the color of an entry is the tree - but I can't get the call and syntax right.

Here's the sample Tk::Tree code:

use Tk; use Tk::Tree; my $mw = MainWindow->new(-title => 'Tree'); my $tree = $mw->Tree->pack(-fill => 'both', -expand => 1); foreach (qw/orange orange.red orange.yellow green green.blue green.yel +low purple purple.red purple.blue/) { $tree->add($_, -text => $_); } # Different things to try here $tree->autosetmode(); MainLoop;
1. Try itemConfigure:
$tree->itemConfigure('orange.red', 0, -foreground => 'blue');
Error:
Bad option `-foreground' at C:/Strawberry/perl/site/lib/Tk.pm line 251 +.
2. Try itemConfigure with a '1' since altering orage.red would be in column 1 of a HList:
$tree->itemConfigure('orange.red', 1, -foreground => 'blue');
Error:
Column "1" does not exist at C:/Strawberry/perl/site/lib/Tk.pm line 25 +1.
3. OK. Try option -fill instead of -foreground because of other observed inconsistencies in Tk:
$tree->itemConfigure('orange.red', 0, -fill => 'blue');
Error:
Bad option `-fill' at C:/Strawberry/perl/site/lib/Tk.pm line 251.

I've tried configure, itemConfigure, entryConfigure (that's for menus) and I'm just not getting it right.

Please help!

Replies are listed 'Best First'.
Re: Tk::Tree how to set color of entry after tree creation
by choroba (Cardinal) on Feb 02, 2024 at 00:15 UTC
    Finding the documentation is a bit tricky. You need to read the following paragraph in Tk::Tree:
    The Tree class is derived from the HList class and inherits all the methods, options and subwidgets of its super-class.

    And Tk::HList shows what we need to do:

    Each list entry in an HList widget is associated with a display item. The display item determines what visual information should be displayed for this list entry. Please see Tk::DItem for a list of all display items.

    Having read Tk::DItem, we can now solve the problem:

    #! /usr/bin/perl use warnings; use strict; use Tk qw{ MainLoop }; use Tk::Tree; use Tk::ItemStyle; my $mw = 'MainWindow'->new(-title => 'Tree'); my $tree = $mw->Tree->pack(-fill => 'both', -expand => 1); $tree->add($_, -text => $_) for qw( orange orange.red orange.yellow ); my $blue = $tree->ItemStyle('imagetext', -foreground => 'blue'); $tree->itemConfigure('orange.red', 0, -style => $blue); MainLoop();

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Thank you - a most excellent answer!

      I missed the HList doc referring to the styles (probably out of frustration but also possibly due to lack of ability to read when interrupted constantly, but I digress), which work perfectly.

      Thanks for the assist!