Message Boards Message Boards

0
|
3637 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Store information from time of Button creation?

Typically when a button uses a variable in its action, it uses the value of that variable at the time the button is triggered. I would like to create a button that stores the information in a variable at the time of its creation for later use in its action. How can this be done?

As a very simple example, If I write the Mathematica code:

Do[Print[Button["press", Print[i]]], {i, 1, 5}]

I get 5 buttons, but rather than printing the numbers 1 to 5 respectively, they print just i, the value of i outside the loop rather than the value of i when the button was created.

I am neither a beginner nor a particularly experienced Mathematica user, but I have already encountered this issue a few times.

POSTED BY: chris tiahrt
2 Replies

Another way is with a replacement rule:

Do[Print[Button["press", Print[p]] /. p -> i], {i, 1, 5}]

You have to circumvent the HoldRest attribute of Button. You can experiment with a simpler situation like this:

Do[Print[Hold[i]], {i, 2}]
Do[Print[Hold[p] /. p -> i], {i, 2}]
Do[Print[Hold[p]] /. p -> i, {i, 2}]
POSTED BY: Gianluca Gorni

Sorry for the pre-mature post -- I thought I was really stuck but I found a solution with a command I had previously not understood well -- the command With. For example

Do[With[{p = i}, Print[Button["press", Print[p]]]], {i, 1, 5}]

This does now print numbers 1 through 5 depending upon the button pressed. I should be able to extend this solution to the more complex situations where I really needed it.

POSTED BY: chris tiahrt
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract