How to implement for loop in .kv file

Viewed 1199

I have written a python code in python file(main.py) to create a kivy app that contains dynamically created labels which works fine. Here is main.py file

main.py

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout

class createLabels(GridLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)        
        self.cols=1
        labels=[Label(text='Label '+str(i)) for i in range(5)]
        [self.add_widget(label) for label in labels]       

class DocApp(App):        
    def build(self):
        return createLabels()

if __name__=="__main__":
    DocApp().run()

However i would like to dynamically create labels similar to the one above using a kivy language file (.kv). I am not sure whether we can use lists and for statements in .kv file. I tried the solution mentioned in one of the similar type question but it didn't work.

1 Answers

You could use on_kv_post which runs when the kv class which you use on_kv_post is ready. And dynamically, like in push of buttons, is basically the same as in the example below.

from kivy.app import App
from kivy.lang import Builder

KV = '''
#: import Label kivy.uix.label.Label

GridLayout:
    cols: 1
    on_kv_post:
        [self.add_widget(Label(text="Label " + str(i))) for i in range(9)]

'''

class TestApp(App):
    def build(self):
        return Builder.load_string(KV)

if __name__ == '__main__':
    TestApp().run()
Related