3
$\begingroup$

I created this progress bar to use in my codes:

progressBar1[var_,total_]:=Row[{ProgressIndicator[var,{0,total}]," ",  
         Row[{NumberForm[100. var/total,{\[Infinity],2}],"%"}],"% ",var}]

But to use it I have to implement like this:

Module[{n = 10, i = 0},
    Print[Dynamic@progressBar1[i, n]];
    (i++; Pause[0.1]) & /@ Range[n];
 ]

I tried to implement like this, but with no success.

progressBar2[var_,total_]:=Print[Dynamic@Row[{ProgressIndicator[var,{0,total}]," ",  
         Row[{NumberForm[100. var/total,{\[Infinity],2}],"%"}],"% ",var}]]

Module[{n=10,i=0},
    progressBar2[i,n];
    (i++;Pause[0.1])&/@Range[n];
]

The idea is to change progressBar2 to make it usable inside Module without necessity to call Dynamic and Print. I've seen this similar post How to create a progress bar? , but didn't get how to upgrade my code.

Some clue?

$\endgroup$
3
  • $\begingroup$ Module[{n = 10, i = 0}, Print@ProgressIndicator[Dynamic[x]]; (i++; Pause[0.1]; x = i/n) & /@ Range[n];] $\endgroup$ Oct 6, 2012 at 19:15
  • $\begingroup$ I changed the post to make it clearer. The idea is to change progressBar2 function, not it implementation. Tks $\endgroup$
    – Murta
    Oct 6, 2012 at 20:05
  • $\begingroup$ The Dynamic@i is unavoidable. You need to tell Mma that something is changing ... $\endgroup$ Oct 6, 2012 at 20:47

1 Answer 1

5
$\begingroup$

Your definition is progressBar2 is essentially correct, but it is evaluating its arguments. This causes the symbol i to disappear from your example as evaluation replaces i with its value. The simplest fix is to SetAttributes[progressBar, HoldFirst].

However, we see that almost all Mathematica controls require us to specify explicit Dynamic wrappers for dynamic variables. The purpose of this convention is to help people reading the code spot parameters that are subject to special dynamic processing. We could follow that convention by making some minor changes to the definition of the progress bar function:

progressBar3[dyn:Dynamic[var_], total_] :=
  Print @ Row[
    { ProgressIndicator[dyn, {0, total}]
    , " "
    , Dynamic @ NumberForm[100. var/total, {\[Infinity], 2}]
    , "% "
    , dyn
    }
  ]

Following convention, callers of this variant must wrap the variable with Dynamic:

Module[{n=10, i=0}
, progressBar3[Dynamic[i], n]
; (i++; Pause[0.1])& /@ Range[n]
;
]

Incidentally, if you wish for the progress bar to disappear when the computation is complete, replace Print in the progress bar function with PrintTemporary.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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