Chazara
Chazara

Reputation: 169

Kivy Update Label Texture

I need to update a group of labels, 1 at a time, but I also need to see the effects of the change, before the function has completed. The desired outcome is a type of loading bar.

As it stands, my code applies the changes all at once, at the end of the function.

(Code simplified for ease of reading)

main.py

def TextAnimation(self):
    #self.ids.??? are labels
    self.ids.x1y1.text = "-"
    self.ids.x2y1.text = "-"
    self.ids.x3y1.text = "-"
    self.ids.x1y1.texture_update()
    self.ids.x2y1.texture_update()
    self.ids.x3y1.texture_update()
    time.sleep(0.2)
    self.ids.x4y1.text = "-"
    self.ids.x5y1.text = "-"
    self.ids.x6y1.text = "-"
    self.ids.x4y1.texture_update()
    self.ids.x5y1.texture_update()
    self.ids.x6y1.texture_update()
    time.sleep(0.2) 

I was under the impression that labelName.texture_update() calls the next frame immediately, instead of waiting for the function to end, but doesn't appear to work as described inside of the documentation;

Warning The texture update is scheduled for the next frame. If you need the texture immediately after changing a property, you have to call the texture_update() method before accessing texture:

    l = Label(text='Hello world')
    # l.texture is good
    l.font_size = '50sp'
    # l.texture is not updated yet
    l.texture_update()
    # l.texture is good now.

Upvotes: 0

Views: 996

Answers (1)

jligeza
jligeza

Reputation: 4693

You should use Clock to schedule label text changes. Consider this code:

test.kv:

#:kivy 1.9.0
Root:
    cols: 1

    Label:
        id: my_label

    Button:
        text: 'animate text'
        on_press: root.animate_text()

main.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock


class Root(GridLayout):

    string = ''

    def animate_text(self):
        Clock.schedule_interval(self.update_label, 0.1)

    def update_label(self, dt):
        self.string += '>'
        self.ids.my_label.text = self.string

        if len(self.string) > 20:
            Clock.unschedule(self.update_label)
            self.string = ''
            self.ids.my_label.text = 'DONE'


class Test(App):
    pass


Test().run()

Upvotes: 1

Related Questions