开发者

How to have procedural code wait for user input from a GUI before continuing?

开发者 https://www.devze.com 2023-01-20 23:06 出处:网络
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 in

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 开发者_如何学Cindicating 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.)


General solution:

flag = false;

your thread:

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

gui thread:

void OnInputEvent() { flag = true; }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消