user11959055
user11959055

Reputation:

Calling Function in Python file from Kivy

So i am new to the KivyMD library so this might be pretty simple to fix, but i cant find the answer anywhere on google.

Python Code

from kivy.lang import Builder
from kivymd.app import MDApp


class MainApp(MDApp):
    def __init__(self, **kwargs):
        self.title = "Finance Fun"
        super().__init__(**kwargs)

    def build(self):
        self.root = Builder.load_file('my.kv')

    def Work(self, instance):
        print("Hello")


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

Kivy Code

BoxLayout:
    orientation: "vertical"

    MDBottomNavigation:
        id: panel

        MDBottomNavigationItem:
            name: "files1"
            text: "Money"
            icon: "cash-plus"

            BoxLayout:
                orientation: "vertical"
                size_hint_y: None
                height: self.minimum_height
                spacing: dp(10)
                pos_hint: {"center_x": .5, "center_y": .5}

                MDFillRoundFlatIconButton:
                    id: work
                    text: "Work"
                    icon: "hammer-wrench"
                    pos_hint: {"center_x": .5}
                    on_release: root.Work()

So if you can see in MDFillRoundFlatIconButton: Im calling on_release: root.Work() which is the function in the python file.

The error that shows up is:

on_release: root.Work()
   File "kivy/weakproxy.pyx", line 32, in kivy.weakproxy.WeakProxy.__getattr__
 AttributeError: 'BoxLayout' object has no attribute 'Work'

If you could help me that would be very appreciated Thank you!

Upvotes: 1

Views: 83

Answers (1)

syntonym
syntonym

Reputation: 7384

In kv lang (what you refer to "Kivy code" in your question) root refers to the root widget, which is in your case a BoxLayout (first line). In your python code you define the Work() function for MainApp. You can refer to your app in kv by app. So your kv should look like the following:

 on_release: app.Work()

What app and root means in a kv file is described here.

Upvotes: 1

Related Questions