KIVY:如何多任务处理

问题描述 投票:-1回答:1

我想在kivy中显示一个加载动画,而其他事情正在进行。怎样才能做到这一点?对不起,我没有示例代码,我只是不知道从哪里开始。

python kivy multitasking
1个回答
0
投票

我也遇到了同样的问题,你可以用线程来实现。

我不知道你想实现什么,但假设你想在点击按钮时加载一些东西。当加载时,你想显示一个弹出式的 "加载"。这里有一个简单的示例程序,可以让你做到这一点。

main.py

import threading
import time

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.label import Label


class ExampleApp(App):
    def show_popup(self):
        # Create and open a popup
        self.loading_pop = Popup(title='Please wait', 
                                 content=Label(text='Loading...'),
                                 size_hint=(.8, .5), auto_dismiss=False)
        self.loading_pop.open()

    def process_btn_click(self):
        self.show_popup() # Open the popup

        # Start a thread, this allows you to display the popup while
        #     running some long task
        my_thread = threading.Thread(target=self.some_long_task)
        my_thread.start()

    def some_long_task(self):
        current_time = time.time()
        while current_time + 3 > time.time():  # 3 seconds
            time.sleep(1)

        # When the task is done, let the popup display "Done!"
        self.loading_pop.content.text = 'Done!'
        # Also let the user click out of the popup now
        self.loading_pop.auto_dismiss = True


if __name__ == '__main__':
    ExampleApp().run()

示例.kv

Screen:
    Button:
        text: 'Click me'
        pos_hint: {'center_x': .5, 'center_y': .5}
        size_hint: .3, .2
        on_release:
            app.process_btn_click()

希望这能回答你的问题

© www.soinside.com 2019 - 2024. All rights reserved.