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



我有这样的问题:

  • 我的应用程序在长函数期间冻结
  • 如果用户在加载过程中多次单击,则会进行多次调用
  • 视觉效果让它看起来像bug
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()

最新更新