Call method from kv file

554 views
Skip to first unread message

Fernando Lima

unread,
May 30, 2022, 3:49:55 PM5/30/22
to Kivy users support
main.kv:

WindowManager:
    Form1:
    Form2:

<Form1>
    name: 'form1'
    BoxLayout:
        Button:
            text: 'Press Me'
            on_press: form1.button_pressed()

<Form2>
    name: 'form2'
    BoxLayout:
        Button:
            text: 'Press Me'
            on_press: form2.button_pressed()

main.py:

import kivy

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

class WindowManager(ScreenManager):
    pass


class Form1(Screen):
    def button_pressed(self):
        print('Form1 button pressed')


class Form2(Screen):
    def button_pressed(self):
        print('Form2 button pressed')


class Main(App):
    def build(self):
        return Builder.load_file('main.kv')

Main().run()


It is simple. I want that when I press the button the kv file call the method in the same class defined in py file. Then if I press the button in Form1 the method button_pressed of the object of type Form1 must be called.

How I do this?

Thanks for your support.

Fernando Lima

unread,
May 30, 2022, 4:06:00 PM5/30/22
to Kivy users support
If I do it in kv file:

<Form1>
    name: 'form1'
    BoxLayout:
        Button:
            text: 'Press Me'
            on_press: self.parent.parent.button_pressed()

Then works, but if I change the layout will stop to work because I need to go upping each level of the hierarchy.
I would like to access the Form1 methods directly.

Is it possible? How?
Thanks a lot for your support.

Fernando Lima

unread,
May 30, 2022, 4:16:04 PM5/30/22
to Kivy users support
I found a solution. Sorry for ask it, I am starting with kivy. But maybe it helps someone more.

If I do it in kv file:

<Form1>
    name: 'form1'
    BoxLayout:
        Button:
            text: 'Press Me'
            on_press: root.button_pressed()

It solves my problem.
Reply all
Reply to author
Forward
0 new messages