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
JavaScript
x
27
27
1
class ScreenOne(Screen):
2
3
def __init__(self):
4
super(ScreenOne, self).__init__()
5
6
def callFunction(self):
7
result = function_takes_awhile(self.answer.text)
8
9
if result != None:
10
self.manager.current = 'screenTwo'
11
12
class ScreenTwo(Screen):
13
pass
14
15
class Manager(ScreenManager):
16
pass
17
18
class MyApp(MDApp):
19
20
def build(self):
21
self.root_widget = Builder.load_file('myapp.kv')
22
23
return self.root_widget
24
25
if __name__ == '__main__':
26
MyApp().run()
27
.kv
JavaScript
1
32
32
1
Manager:
2
ScreenOne:
3
ScreenTwo:
4
5
<ScreenOne>
6
name: "screenOne"
7
8
answer: answer
9
spinner: spinner
10
11
MDBoxLayout:
12
orientation: "vertical"
13
14
Screen:
15
MDBoxLayout:
16
MDTextField:
17
id: answer
18
hint_text: "Answer"
19
20
MDSpinner:
21
id:spinner
22
active: False
23
24
MDFlatButton:
25
text="Submit"
26
on_press:
27
spinner.active = True
28
root.callFunction()
29
30
<ScreenTwo>
31
name: "screenTwo"
32
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
,
JavaScript
1
8
1
def start_background_task(self):
2
threading.Thread(target = self.callFunction).start()
3
4
def callFunction(self, *args):
5
result = function_takes_awhile(self.answer.text)
6
if result != None:
7
self.manager.current = 'screenTwo'
8
Then in .kv
,
JavaScript
1
6
1
MDFlatButton:
2
text: "Submit"
3
on_press:
4
spinner.active = True
5
root.start_background_task()
6