NickTsonis
NickTsonis

Reputation: 73

How to use a looping function to update python Kivy application

I have created a program that is based on a looping function. Every time it loops I want to update two labels in the screen. The problem is I use a button to call the function and it does not update the labels until the function stops executing. Lest say I have a label and I call a looping functions that adds from 0 to infinity. I want the label to update in every number. Is this possible?

EDIT: the problem solved using Clock.schedule_interval(function, time) (time in seconds) Just a simple app that adds a number every second and displays it to the screen

Code:

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock
from time import sleep


class Window(GridLayout):
    def __init__(self, **kwargs):
        super(Window, self).__init__(**kwargs)
        self.cols = 1
        self.cnt = 0
        self.btn = Button(text='Start')
        self.add_widget(self.btn)
        self.btn.bind(on_press=self.pressed)
        self.lbl = Label()
        self.add_widget(self.lbl)

    def starting(self, instance):
        self.lbl.text = str(self.cnt)
        self.cnt += 1
        sleep(1)

    def pressed(self, instance):
        Clock.schedule_interval(self.starting, 0)


class MainApp(App):
    def build(self):
        return Window()


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

Upvotes: 0

Views: 886

Answers (1)

inclement
inclement

Reputation: 29450

You've written code that starts looping, then does nothing else until the looping is done. Instead you need to write code that loops once, then lets the gui update, then is run again some time later.

This is straightforward using Clock.schedule_interval:

Clock.schedule_interval(your_function, time_delta)  # time_delta is in seconds, the function is run whenever this amount of time has elapsed

The your_function should perform a single iteration of your loop.

Upvotes: 2

Related Questions