Api正在停止



我正在创建一个Ai/Api,当我问问题时,它用来停止窗口,现在它冻结了。除了我不能输入不止一次之外,我一直在工作。我正在使用PySimpleGui作为我的gui窗口创建者。我找不到如何修复它。它只是停止冻结仍然打开的窗口,但当我尝试使用该应用程序时会关闭。我不应该使用输入吗?

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"未在事件循环中处理,但已中断
  • 从事件循环中断后,窗口未关闭
  • 查询可能需要很长时间,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

相关内容

  • 没有找到相关文章

最新更新