简体   繁体   中英

Kivy Popup Appearing after function is run instead of before

I want to display a popup or modal that says something along the lines of 'please be patient while processing' while the application is performing a function in the background. However the popup appears after the background function has already happened. Below is an example of code that produces this problem.

import os
import time

from kivy.app import App
from kivy.uix.modalview import ModalView
from kivy.uix.popup import Popup
from kivy.uix.button import Button, Label


class Poppy(Popup):
    def __init__(self, **kwargs):
        super(Poppy, self).__init__(**kwargs)
        self.content = Label(text='working')
        self.open()
        print("Working...")

class TApp(App):
    def build(self):
        return Button(text="Click to run", on_press=self.modal_test)

    def modal_test(self, event):
        p = Poppy(size_hint=(0.5, 0.5))
        self.printer()

    def printer(self):
        print('Popup works')
        time.sleep(5)

TApp().run()

You should not execute a time-consuming task on the same GUI thread as it blocks the eventloop causing the GUI to not run correctly. In these cases you must run it in a new thread.

import threading
# ...
class TApp(App):
    def build(self):
        return Button(text="Click to run", on_press=self.modal_test)

    def modal_test(self, event):
        p = Poppy(size_hint=(0.5, 0.5))
        threading.Thread(target=self.printer, daemon=True).start()

    def printer(self):
        print('before: Popup works')
        time.sleep(5)
        print('after: Popup works')
# ...

It is also advisable to check Working with Python threads inside a Kivy application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM