Skip to main content
5 of 5
replaced http://mathematica.stackexchange.com/ with https://mathematica.stackexchange.com/

Why do buttons with ChoiceDialog freeze the front end?

Pressing the button below will freeze my front end. An unpainted white dialog box comes up, then it completely freezes, and I need to forcibly kill the front end. CPU usage stays at zero during this.

Button["Ask", If[ChoiceDialog["OK?"], Print["OK!"]]]

Why does this happen?

What is the proper way to ask for confirmation before an action?


Answers:

My first question has been answered below and in the comment by @JohnFultz: use Button[..., Method -> "Queued"]. But this will make a button which doesn't work while evaluations are ongoing.

I need a button which works even during evaluations. I came up with the following solution:

Button["Ask", 
 CreateDialog[
  Column[{"OK?", 
    ChoiceButtons[{"OK"}, {Print["OK!"]; DialogReturn[]}]}]]]

CreateDialog returns immediately without waiting for an input, so the front end is not blocked. The functionality is moved completely into the dialog's button.

You can test that the button works and reacts immediately even while Pause[10] is evaluating.


Quoting the two most enlightening comments:

The "Preemptive" method interrupts queued (e.g., Shift+Enter) evaluations to do its work and cannot itself be interrupted. I.e., you can't preempt a preemptive calculation. ChoiceDialog is putting up an interface which independently needs the attention of the Mathematica kernel, but can't get it because Button has the kernel's sole attention - John Fultz

 

Button[..., Method->"Preemptive"] (the default Method value) and InputString[] are effectively exactly the opposite of each other. Button[..., Method->"Preemptive"] will pause the user interface (causing it to stop responding to events) until the computation is complete. InputString[] will pause the computation until the user has input some value. When you combine these two the user interface is waiting for the computation to complete while at the same time the computation is waiting for user interface input. - ragfield

Szabolcs
  • 236.5k
  • 31
  • 641
  • 1.3k