Alex DS
Alex DS

Reputation: 101

Python - Kivy: Label does not update during a function excution

I saw that there are other topics related to this one but I could make this simple project to work. I need a label to be updated with the function status while it is running just to let the user know that the program still working while the function is processing, but the label is only updated when the function is completed

Here are the files

my.kv

WindowManager:
    ChangeLabel:
<ChangeLabel>:
    BoxLayout:
        orientation: 'vertical'
        padding: 200, 20
        Label: 
            id: labeltxt
            text: 'Text to change'
            font_size: 30           
            height: 50
        Button:
            text:'Run Function'
            size_hint_y: None
            height: 30
            on_release:
                root.changeLabel()
        Label: 

test.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.core.window import Window
import time
from kivy.clock import Clock

class ChangeLabel(Screen):
    def changeLabel(self):
        Clock.schedule_once(self.test)

    def test(self, dt):
        self.ids.labeltxt.text = 'Function is running...'#I wanna this in lablel while function is running
        time.sleep(2)# function to run
        self.ids.labeltxt.text = 'Completed'


class WindowManager (ScreenManager):
    pass

kv = Builder.load_file('my.kv')
class MyApp(App):
    def build(self):
        return kv

MyApp().run()

Upvotes: 1

Views: 34

Answers (1)

Alex DS
Alex DS

Reputation: 101

I did this solution, now it is working the way I want, but not sure if this is the best way.

test.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang.builder import Builder
from kivy.core.window import Window
import time
from kivy.clock import Clock

class ChangeLabel(Screen):
    i = 0
    def changeLabel(self):
        Clock.schedule_interval(self.test, 0.05)

    def test(self, dt):
        if self.i == 0:
            self.ids.labeltxt.text = 'Function is running...'
            self.i = 1
        else:
            time.sleep(2)# function to run
            self.ids.labeltxt.text = 'Completed'
            self.i = 0
            Clock.unschedule(self.test)

class WindowManager (ScreenManager):
    pass

kv = Builder.load_file('my.kv')
class MyApp(App):
    def build(self):
        return kv

MyApp().run()

Upvotes: 1

Related Questions