Kivy:加载长函数动画(避免冻结)

2024-04-21

我有这样的问题:

  • 我的应用程序在长函数期间冻结
  • 如果用户在加载过程中多次单击,则会进行多次调用
  • 视觉上让它看起来很大

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()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kivy:加载长函数动画(避免冻结) 的相关文章

随机推荐