Api 正在停止

Api is stopping

我正在创建一个 Ai/Api 它曾经在我问问题时停止 window 现在它冻结了。除了不能输入多次外,我可以正常工作。我使用 PySimpleGui 作为我的 gui window 创建者。我找不到如何修复它。它只是停止冻结 windows 仍然打开但在我尝试使用该应用程序时关闭。我不应该使用输入法吗?

    import wolframalpha
from wolframalpha import Client
client = Client('Y4W6A9-P9WP4RLVL2')




import PySimpleGUI as sg                       
sg.theme('Dark Blue')

layout = [  [sg.Text("Hello, my name's Ted. What's your question?")],   
            [sg.Input()],
            [sg.Button('Ok'), sg.Button('Cancel')],
            [sg.Output()]   ]


window = sg.Window('Ted', layout)      

while True:
    event, values = window.read()   
    if event in (None, 'Ok'):

    break

res = client.query(values[0])
answer = next(res.results).text

input(answer)

这里有些问题,

  • 事件'Ok'未在事件循环中处理,但从中中断。
  • Window 退出事件循环后未关闭。
  • 查询可能耗时较长,GUI无响应,需要多线程。

示例代码

import threading
import PySimpleGUI as sg
from wolframalpha import Client

def find_answer(window, question):
    res = client.query(question)
    answer = next(res.results).text
    if not window.was_closed():
        window.write_event_value('Done', (question, answer))

client = Client('Y4W6A9-P9WP4RLVL2')

font = ("Courier New", 11)
sg.theme("DarkBlue3")
sg.set_options(font=font)

layout = [
    [sg.Text("Hello, my name's Ted. What's your question?")],
    [sg.Input(expand_x=True, key='Input'), sg.Button('Ok'), sg.Button('Exit')],
    [sg.Multiline(size=(80, 20), key='Output')],    # Suggest to use Multiline, not Output
]

window = sg.Window('Ted', layout, finalize=True)
entry, output, ok = window['Input'], window['Output'], window['Ok']
entry.bind('<Return>', ' Return')                   # Input will generate event key+' Return' when hit return

while True:

    event, values = window.read()

    if event in (sg.WINDOW_CLOSED, 'Exit'):
        break

    elif event in ('Ok', 'Input Return'):           # Click button `Ok` or hit Enter in Input
        question = values['Input'].strip()
        if question:
            ok.update(disabled=True)                # In handling, stop next question
            output.update('Checking ...')           # Message for user to wait the result
            # Threading required here for it take long time to finisih for this enquiry
            threading.Thread(target=find_answer, args=(window, question), daemon=True).start()
        else:
            output.update('No question found !')    # No content in Input

    elif event == 'Done':                           # Event when this enquiry done
        question, answer = values['Done']           # result returned by window.write_event_value from another thread
        output.update(f'Q:{question}\nA:{answer}')  # Update the result
        entry.Update('')                            # Clear Input for next question
        ok.update(disabled=False)                   # Enable for next question

window.close()                                      # Close window before exit