Accessing widgets defined inside the Kv language in your Python code

This recipe will teach you how to access definitions inside the Kv language in your Python code and vice versa.

Getting ready

This recipe will use button, a very common widget that we also used in the last recipe.

How to do it…

This recipe follows as:

  1. Make a rule for the widget.
  2. Define a button.
  3. Give it an ID.
  4. Define the label for the button.
  5. In the action, call a method in the Python code:
    <MyW>:
        Button:
            id: b1
            text: 'Press to smash'
            on_release: root.b_smash()
  6. Create the Python code with the method:
    import kivy kivy.require('1.8.0') # replace with your current kivy version ! from kivy.app import App from kivy.uix.widget import Widget class MyW(Widget): def b_smash(self): self.ids.b1.text ...

Get Kivy Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.