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

3

我有这样的问题:

  • 我的应用在长时间运行函数期间会冻结
  • 如果用户在加载期间多次点击,它会发出多个调用
  • 视觉效果使其看起来像是一个错误
1个回答

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


1
真正的答案是“这不是一个好主意,找另一种方式。”没有无解的问题,只有糟糕的问题^^ - Utopion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接