Python KivyMD- 在等待函数结果时加载微调器

Python KivyMD- load spinner while waiting for results from a function

我正在尝试添加 MDSpinner 小部件,同时等待外部函数生成 return 结果,因为它需要几秒钟才能完成执行。我的问题是按下按钮时微调器没有加载。如何在等待 return 结果的函数时显示微调器?

我当前的代码如下所示:

.py

class ScreenOne(Screen):

 def __init__(self):
  super(ScreenOne, self).__init__()

 def callFunction(self):
  result = function_takes_awhile(self.answer.text)
      
  if result != None:
   self.manager.current = 'screenTwo'

class ScreenTwo(Screen):
 pass

class Manager(ScreenManager):
 pass

class MyApp(MDApp):

 def build(self):
  self.root_widget = Builder.load_file('myapp.kv')

  return self.root_widget

if __name__ == '__main__':
 MyApp().run()

.kv

Manager:
 ScreenOne:
 ScreenTwo:

<ScreenOne>
 name: "screenOne"

 answer: answer
 spinner: spinner

 MDBoxLayout:
  orientation: "vertical"
 
  Screen:
   MDBoxLayout:
    MDTextField:
     id: answer
     hint_text: "Answer"
   
    MDSpinner:
     id:spinner
     active: False

    MDFlatButton:
     text="Submit"
     on_press:
      spinner.active = True
      root.callFunction()

<ScreenTwo>
 name: "screenTwo"

想法是在不同的线程上执行任何任务(除了 UI 上的进程),允许主线程上的 UI 到 运行。

您可以通过创建一个类似于以下内容的新线程来实现它:

首先创建一个新方法,比如说,start_background_task in .py,

    def start_background_task(self):
        threading.Thread(target = self.callFunction).start()

    def callFunction(self, *args):
        result = function_takes_awhile(self.answer.text)
        if result != None:
            self.manager.current = 'screenTwo'

然后在.kv,

                MDFlatButton:
                    text: "Submit"
                    on_press:
                        spinner.active = True
                        root.start_background_task()