Skip to content Skip to sidebar Skip to footer

Kivy: Loading Animation For Long Function (avoid Freeze)

I have this kind of problems: my application freeze during the long function if the user click multiple times during the loading, it makes multiple calls the visual makes it looks

Solution 1:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.floatlayout import MDFloatLayout
from time import sleep
from threading import Thread
from functools import partial

KV = """
MDFloatLayout:
    Button:
        id: btn
        text: "Hello World"

<LoadingLayout>
    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size
    MDSpinner:
        size_hint: .05, .05
        pos_hint: {'center_x': .5, 'center_y': .5}
"""

class LoadingLayout(MDFloatLayout):

    def on_touch_down(self, touch): #Deactivate touch_down event
        if self.collide_point(*touch.pos):
            return True

class ExampleApp(MDApp):
    loading_layout = None

    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        self.loading_layout = LoadingLayout()
        self.root.ids["btn"].bind(on_press=partial(self.launch_thread,self.func_that_take_time)) #call on click
        #self.launch_thread(self.func_that_take_time) #call normally

    def launch_thread(self, func, w=None):
        self.root.add_widget(self.loading_layout)
        Thread(target=self.my_thread, args=(func,), daemon=True).start()

    def func_that_take_time(self):
        print("Beginning of the function that I want to thread !!!")
        for i in range(1,11):
            print(f"{10-i} seconds till end")
            sleep(1)
        print("End of the function that I want to thread !!!")

    def my_thread(self, func):
        func()
        self.root.remove_widget(self.loading_layout)

ExampleApp().run()


Post a Comment for "Kivy: Loading Animation For Long Function (avoid Freeze)"