Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Strange behavior of iteration while creating Perl/Tk widgets dynamicallyby kcott (Archbishop) |
on Oct 29, 2021 at 10:16 UTC ( [id://11138196]=note: print w/replies, xml ) | Need Help?? |
G'day Zsolt, You have written your for loop like this:
The following is very important. I'm not attempting to be patronising; you need to fully understand this. Pay close attention to the numbers.
In each iteration, you set up two callbacks with the -command option. In both cases, the value of the callback is a coderef (an anonymous subroutine: sub { ... }); You redefine those coderefs on each iteration. The code in those coderefs contains the variable $i. On the final redefinition, the last value that $i has is 6! This is why, regardless of which CLR button you use, you always see "title: Choose color for 6 degree!"; and similarly, regardless of which CHK button you use, you always see "degreeClr6". Using (non-reference) variables in a callback is almost always a bad idea in Tk applications: use references instead. Here's a somewhat contrived Tk application using two scalarrefs and an arrayref in a callback. It's possibly a little over the top; however, it's intended to make a point.
The swatch at the top starts off black. As you click on any of the five coloured buttons below, it takes on the colour of that button. You have no end of other problems with the code you posted: package variables springing into existence all over the place; symbolic references which you should really avoid (arrays and hashes are often a better choice — see @colours in my code above); lines so long that they're almost unreadable (one statement has 262 characters); and other code which I suspect you just threw at it in the hope that it would somehow fix something (for instance, what did think the utf pragma would achieve?). I strongly recommend that you read perlintro to get a basic grounding in Perl coding. Following that, you may want to look at: "Symbolic references", "Anonymous Subroutines", and Tk::callbacks. — Ken
In Section
Seekers of Perl Wisdom
|
|