【问题标题】:How to have procedural code wait for user input from a GUI before continuing?如何让程序代码在继续之前等待来自 GUI 的用户输入?
【发布时间】:2010-10-19 12:45:07
【问题描述】:

在我的程序中有一个复杂的计算,需要用户评估中间结果。这在命令行应用程序(这就是我的代码现在的样子)中效果很好,因为交互式提示会暂停程序执行,直到用户按下回车键。命令行代码如下所示:

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

我想提供一个比命令行更直观的界面,方法是使用 GUI 并允许用户单击指示他们选择的按钮而不是输入它。我正在描绘这样的画面:

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

有没有一种方法可以暂停执行计算的程序代码,然后在用户单击按钮后恢复代码?我不太确定如何在这里引发或处理事件,因为通常在 GUI 中,控制回调是代码执行的起点,但在这里,代码从其他地方开始,需要屈服于 GUI 并从 GUI 恢复。

(如果有什么不同,我使用的是 Python 和 wxPython。)

【问题讨论】:

    标签: user-interface design-patterns language-agnostic


    【解决方案1】:

    一般解决方案:

    flag = false;
    

    你的帖子:

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

    gui 线程:

    void OnInputEvent() { flag = true; }
    

    【讨论】:

    • 这不是线程安全的一般来说 - 你需要一个内存屏障来确保flag=true之前GUI线程的写入对非GUI可见在while(!flag); 之后立即线程 - 当然,如果幸运的话,它有时可能会在某些平台上工作,例如 python。
    • 内存读取通常是线程安全的,不是吗?我不明白你的意思,请详细说明。
    【解决方案2】:

    我不是 python 程序员,但通常这意味着您需要偶尔等待 GUI 线程,直到该线程收到用户的输入。

    可能有更简洁的pythonesque api可用,但你当然可以使用raw python events

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多