Laurent
Laurent

Reputation: 160

Is it possible to call a function from another class in the kv file?

I have a popup window that I created with a class. In this popup, I have 2 buttons. Depending on the button you press, it has to call a function which is in the main class.

If you call a function in the kv file with "on_release:" which is in the same class, you write "root....()". What should I write if I want to call one of the functions from another class?

Thank you

Upvotes: 0

Views: 1498

Answers (1)

John Anderson
John Anderson

Reputation: 38857

In your kv you can reference app, self, or root. See documentation. So, if you have a reference to OtherClass in any of those, you can use that reference in kv. For example, if in your App class you include a line:

self.otherClassRef = OtherClass()

then in your kv you can use

on_release: app.otherClassRef.someMethod()

Regardless, you must have a reference to an instance of OtherClass to access instance methods.

You can access static methods using

on_release: OtherClass.someStaticMethod()

or an instance method using

on_release: OtherClass().someMethod()

but you will likely need to import OtherClass in your kv. Something like

#:import OtherClass OtherClassFileName.OtherClass

Note that if you do OtherClass().someMethod() you are creating a new instance of OtherClass, not using any currently existing instance.

Upvotes: 2

Related Questions