【问题标题】:Kivy: Loading animation for long function (avoid freeze)Kivy:为长功能加载动画(避免冻结)
【发布时间】:2021-07-14 10:58:55
【问题描述】:

我有这样的问题:

  • 我的应用程序在长功能期间冻结
  • 如果用户在加载过程中多次点击,会进行多次调用
  • 视觉效果使它看起来像错误

【问题讨论】:

    标签: python multithreading kivy kivymd


    【解决方案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()
    
    

    【讨论】:

    • 真正的答案是“这不是个好主意,换个方式。”没有没有答案的问题,只有不好的问题^^”
    猜你喜欢
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2017-11-02
    • 1970-01-01
    • 2012-06-27
    • 2016-02-21
    相关资源
    最近更新 更多