views:

38

answers:

2

In my program there is a complex calculation that requires the user to evaluate intermediate results. This works well in a command line application (which is what my code looks like now) because the interactive prompt halts the program execution until the user hits enter. The command line code looks something like this:

def calculate(starting):
    result1 = initial_calculation(starting)
    user_input1 = input("What is your choice for " + result1 + "?")
    result2 = calculate1(user_input1)
    user_input2 = input("What is your choice for " + result2 + "?")
    result2 = calculate2(user_input2)
    #...etc

I would like to provide a more intuitive interface than is possible with the command line by using a GUI and allowing the user to click on a button indicating their choice instead of typing it in. I'm picturing something like this:

def do_something(starting):
    result1 = initial_calculation(starting)
    #wait for user to press a button indicating their choice?
    result2 = calculate1(clicked_button.user_input1)

    label.text("What is your choice for " + result1 + "?")
    #wait for user again
    result2 = calculate2(clicked_button.user_input2)
    #...etc

Is there a way I can pause the execution of the procedural code that does the calculations and then resume the code after the user clicks a button? I'm not really sure how to raise or handle events here because normally in a GUI the control callbacks are the starting point for code execution, but here, the code starts elsewhere and needs to yield to and resume from the GUI.

(If it makes a difference, I am using Python and wxPython.)

+1  A: 

I'm no python programmer, but in general that means you'll need to occasionally wait for the GUI thread until that thread has received input from the user.

There may well be a more succinct, pythonesque api available, but you can certainly use raw python events.

Eamon Nerbonne
+1  A: 

General solution:

flag = false;

your thread:

while (!flag); // wait here, consume cpu doing nothing

gui thread:

void OnInputEvent() { flag = true; }
Grozz
This is not thread safe *in general* - you need a memory barrier in there somewhere to ensure that writes by the GUI thread before `flag=true` are visible to the non-GUI thread *immediately* after `while(!flag);` - of course, it might work, if you're lucky, sometimes, on some platforms, perhaps such as python.
Eamon Nerbonne
Memory reads are generally threadsafe, aren't they? I don't get your point, please elaborate.
Grozz