MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Variable amount of Buttons in Mathematica

  • To: mathgroup at smc.vnet.net
  • Subject: [mg92902] Re: Variable amount of Buttons in Mathematica
  • From: David Bailey <dave at Remove_Thisdbailey.co.uk>
  • Date: Fri, 17 Oct 2008 05:25:25 -0400 (EDT)
  • References: <gcscrf$8l3$1@smc.vnet.net>

SDY wrote:
> I'm pretty new to this...
> 
> I'm trying to write a function that will create a variable number of buttons (based on some input) and relate each button to a function call with a unique parameter value. For example:
> 
> array = {1, 2, 3, 4, 5};
> Column[{Row[
>    Table[Button[array[[n]], Print[n], ImageSize -> {50, 50}], {n, 1,Length[array], 1}]]}]
> 
> Gives me five buttons, labeled 1-5, but each prints 'n' when clicked on.  
> How would I change this to print the value of n?
> 
> My best guess at this point is that there is a scoping issue with n, but I don't have enough Mathematica experience to know how to assign static values...
> 
> 
> Thanks
> 
The issue here is that the expression to be evaluated in the Button 
construct is not evaluated until the button is pressed (which makes good 
sense when you think about it!). At this point, n does not have a value. 
One easy way to solve this is to use 'With' to inject the value of n 
inside the expression on each iteration of the Table construct:

array = {1, 2, 3, 4, 5};
Column[{Row[
    Table[With[{n = n},
      Button[array[[n]], Print[n], ImageSize -> {50, 50}]], {n, 1,
      Length[array], 1}]]}]

Note that you can confirm that Button only evaluates its first argument 
by evaluating:

Attributes[Button]

David Bailey
http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: labeling axes in a ContourPlot
  • Next by Date: Re: Import["http://.."] wackiness.... ?
  • Previous by thread: Re: Re: Variable amount of Buttons in Mathematica
  • Next by thread: Re: Variable amount of Buttons in Mathematica