in reply to Tk -textvariable doesn't change when Entry widget changes

Using the array-ref style of -command is tricky and has limited usefulness, so I'll show you how to do it using an Entry with -textvariable, and using a Button -command with a real sub.

First, when using -textvariable, you want to give a reference to the variable, like so:

my $original_x = 3; my $user_x = $f1->Entry( -textvariable => \$original_x )->pack;

Then, whenever $original_x is tested/printed/etc., it contains whatever is currently in the entry box.

Here's a good way to use -command:

$mw->Button( -command => \&print_entries )->pack; sub print_entries { my $val = $user_x->cget('-text'); print "$val\n"; }

The salient facts are these:

  1. You should call cget on '-text', not '-textvariable'.
  2. The call to cget should be "delayed" until the time the button is pressed, not when it is created. In your form, cget was being called at creation time.
You could call cget('-textvariable'), but that returns a reference to the variable, not the current value. So you'll need to dereference it, like so:

sub print_entries { my $var_ref = $user_x->cget('-textvariable'); my $val = $$var_ref; print "$val\n"; }
Of course, in this simple program you showed, you don't need to do either of those things, because you already have the variable in scope:
sub print_entries { print "$original_x\n"; }
(assuming you've used the -textvariable option as above.)

Replies are listed 'Best First'.
Re^2: Tk -textvariable doesn't change when Entry widget changes
by Petras (Friar) on Sep 26, 2005 at 03:08 UTC
    Thank you, jdporter for a right solution! I was trying to use @_ in the sub and not getting what I thought I would. I was passing variables to the sub because, coming from another language, I thought scope would be an issue referencing the variables that were modified in a different block. Thanks!

    Cheers!
    --p


    Don't worry about people stealing your ideas. If your ideas are any good, you'll have to ram them down people's throats.

    -Howard Aiken