4
$\begingroup$

Is it possible to save information from a toggler bar to a variable when a button is clicked?

Example:

I have a toggler bar with its buttons numbered, say 1–4. When I press on a the button showing 1, I would like to have 1 saved to variable x. When I press the button showing 2 is pressed, I would like 2 saved to variable y. And so on.

$\endgroup$
  • 1
    $\begingroup$ Does using the second argument of Dynamic work for you? E.g. TogglerBar[Dynamic[x,caching_function],choices]? The caching_function could just set the value passed to a variable, as you wanted. $\endgroup$ – b3m2a1 Dec 13 '16 at 7:06
7
$\begingroup$

I think this does what you want. a is the control variable and x, y, and z are controlled by the togglers.

TogglerBar[
  Dynamic[a, (a = #; Clear[x, y, z]; ReleaseHold[#]) &],
  {Hold[x = 1] -> 1, Hold[y = 2] -> 2, Hold[z = 3] -> 3}
]

Dynamic[{x, y, z}]

enter image description here

If that does what you want here is a utility function to make using it easier.

SetAttributes[myToggles, HoldFirst]

myToggles[var_, val_] := myToggles[var, val, val]

myToggles[{var__Symbol}, val : {__}, lbl : {__}] :=
  Module[{a},
    TogglerBar[
      Dynamic[a, (a = #; Clear[var]; ReleaseHold[#]) &], 
      MapThread[
        Function[, Hold[# = #2] -> #3, HoldAll],
        Unevaluated @ {{var}, val, lbl}
      ]
    ]
  ]

Examples:

myToggles[{a, b, c}, {1, 2, 3}]
Dynamic[{a, b c}]

myToggles[{m, n, o}, {1, 2, 3}, {"one", "two", "three"}]
Dynamic[{m, n, o}]
$\endgroup$
  • 1
    $\begingroup$ This is marvelous code, whether it does what the OP wants or not. $\endgroup$ – m_goldberg Dec 13 '16 at 16:35
  • $\begingroup$ @m_goldberg Thank you. :-) $\endgroup$ – Mr.Wizard Dec 13 '16 at 21:19
  • $\begingroup$ This is perfect, this is exactly what I needed . Thank you very much!! $\endgroup$ – Joshua Hernandez Dec 15 '16 at 20:05
  • $\begingroup$ @JoshuaHernandez I am glad I could help. :-) Since this fully meets your needs please consider Accepting my answer. $\endgroup$ – Mr.Wizard Dec 16 '16 at 0:04
3
$\begingroup$

If you are willing to use an indexed variable to track the buttons pressed on the bar, fairly simple code will work.

Clear[bar, b]
bF = (bar = #; Clear[b]; Evaluate[b /@ #] = #) &;
With[{nBtns = 5},
  Column[
    {TogglerBar[Dynamic[bar, bF], Range[nBtns]],
     Dynamic[b /@ Range[nBtns]]}]]

bar

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.