in reply to binding Tk textvariables

You can use the size() method of the Listbox object to retrieve the number of elements in the Listbox. You can use this value for the -text option of the Label object or you can store it in a variable.

Assuming you don't have any need to store the number of items in the Listbox in a variable for other needs, the following code sample will dynamically update the Label widget as items are added and removed from the Listbox.

#!/usr/bin/perl use strict; use Tk; my $mw = MainWindow->new(qw/-width 300 -height 200/); my $lb = $mw->Listbox(-selectmode => "multiple")->pack(); my $label = $mw->Label(-text => "Empty")->pack(); my $add = $mw->Button(-text => "add item", -command => \&add )->pack(); my $delete = $mw->Button(-text => "delete item", -command => \&delete, )->pack(); MainLoop; sub add { $lb->insert('end', "item"); $label->configure(-text => "num elms = " . $lb->size()); } sub delete { my @elms = $lb->curselection; foreach (@elms) { $lb->delete($_); } $label->configure(-text => "num elms = " . $lb->size()); } exit;
hope this helps,
davidj

Replies are listed 'Best First'.
Re^2: binding Tk textvariables
by Anonymous Monk on Jun 18, 2004 at 13:06 UTC
    Thanks for your suggestion. This clearly works, but it's the kind of thing I was hoping to avoid as I already have several subs that modify the number of elements in the listbox, and I was hoping to avoid having to chase down every place that happened. I should have made this more clear in the question. This does suggest a solution where any any subroutine that modifies the size of the listbox is required to use something like your add or delete to do so - but that would have required some forethought ;)