alkopop79
alkopop79

Reputation: 539

How to add an id in Kivy's .kv file?

I'm struggling to come up with a simple example for using IDs. Later I want to use the IDs to change parameters, for instance to change the text in a label or a button. So how do I get started? I can't find simple example for using IDs.

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

class TestApp(App):
    pass

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

The .kv file:

#:kivy 1.0

Button:
    text: 'this button \n is the root'
    color: .8, .9, 0, 1
    font_size: 32

    Label: 
        text: 'This is a label'
        color: .9, 0, .5, .5

In this case I would like to use an ID for the label and be able to change the text.

Upvotes: 2

Views: 1515

Answers (1)

joscha
joscha

Reputation: 1183

You can find some info about the kv language here. You need to use kivy properties for that.

here is an example on how you can change the label text when you press the button: python file:

import kivy
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.properties import ObjectProperty

class GridScreen(GridLayout):
    label = ObjectProperty() #accessing the label in python
    def btnpress(self):
        self.label.text = 'btn pressed' #changing the label text when button is pressed

class TestApp(App):
    def build(self):
        return GridScreen()

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

kv file:

<GridScreen>:
    label: label #referencing the label
    rows: 2
    Button:
        text: 'this button \n is the root'
        color: .8, .9, 0, 1
        font_size: 32
        on_press: root.btnpress() #calling the method 

    Label:
        id: label
        text: 'This is a label'
        color: .9, 0, .5, .5

Upvotes: 2

Related Questions