1
$\begingroup$

I believe I am missing an important piece of information. I am trying to execute a simple If statement inside a DynamicModule. The variable tested in the If statement is a Dynamic variable, in this case, a Number. As it can be seen from the elementary (but wrong) few lines of code the If statement does not work because the tested variable "active" is not a Number (NumberQ=False).

DynamicModule[{active = 0},

 If[active == 0, color = Green, color = Red];

(*--- Output and Dynamic Input ---*)

 Column[
  {

   Panel[Style["Result", color, Bold]],

   Panel[Row[{"Setting@active= ", Setting@active, "  ", 
      "NumberQ[Setting@active]= ", NumberQ[Setting@active]}]],

   Panel[Row[{"Dynamic[active]= ", Dynamic[active], "   ", 
      "NumberQ[Dynamic[active]]= ", NumberQ[Dynamic[active]]}]],

   Button["Set active=True", active = 1;, Method -> "Queued", 
    Background -> Green],

   Button["Set active=False", active = 0;, Method -> "Queued", 
    Background -> Red]

   }]

]

I assume the issue is trivial ... but as I said, I think I am missing a basic piece of knowledge here. Any assistance is most appreciated. Many thanks in advance.

$\endgroup$
  • $\begingroup$ Unlike Manipulate the body of DynamicModule does not refresh on any changes. You need to take care of that, change color in Buttons or take a look at DynamicWrapper. $\endgroup$ – Kuba Jul 26 '17 at 10:47
3
$\begingroup$

You're actually really close. DynamicModule is just a scoping construct that localizes variables: it does not actually make your output dynamic. To do that you need (surprise, surprise) Dynamic. Just wrapping Dynamic around the whole contents of your DynamicModule will make your code work:

DynamicModule[{active = 0},

 Dynamic[
  If[active === 0, color = Green, color = Red];

(*--- Output and Dynamic Input ---*)

 Column[
  {

   Panel[Style["Result", color, Bold]],

   Panel[Row[{"Setting@active= ", Setting@active, "  ", 
      "NumberQ[Setting@active]= ", NumberQ[Setting@active]}]],

   Panel[Row[{"Dynamic[active]= ", Dynamic[active], "   ", 
      "NumberQ[Dynamic[active]]= ", NumberQ[Dynamic[active]]}]],

   Button["Set active=True", active = 1;, Method -> "Queued", 
    Background -> Green],

   Button["Set active=False", active = 0;, Method -> "Queued", 
    Background -> Red]

   }]
  ]

]

As a final word of wisdom: when you're using If in Mathematica, please use === to test for equality instead of ==. The reason for this is that == stands for mathematical equality and not syntactic equality. Sometimes both will work, but == will not always evaluate to True or False and what that happens, If will not evaluate either (unless you use the 4th argument of If).

$\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.