I am trying to add an MDSpinner widget while waiting for an external function to return results since it takes a couple of seconds to finish executing. My problem is the spinner isn’t loading when the button is pressed. How can I show a spinner while waiting for a function to return results?
my current code looks something like this:
.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"
Advertisement
Answer
The idea is to do any task (apart from the processes on the UI) on a different thread allowing the UI to run on the mainthread.
You can implement that by creating a new thread something like the following:
First create a new method, say, 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'
Then in .kv
,
MDFlatButton: text: "Submit" on_press: spinner.active = True root.start_background_task()