Ben Haysome
Ben Haysome

Reputation: 115

Referencing a Function From Another Class in Kivy

So this is my code and what it does:

Label:
    id: easyscore
    text: "0"
    font_size: 44
    bold: True
    color: [1, 1, 1, 1]

This label is on a screen class called easy and it counts the score.

Button:
    text: "Restart"
    font_size: 32
    bold: True
    color: [1, 1, 1, 1]
    background_normal: ""
    background_color: [0.31, 0.4, 0.63, 1]
    on_release: root.rst_gmvr()

This button is on a screen class called gameovereasy and when it is released it should change the screen back to easy and reset the score counter back to zero.

The previous 2 blocks of code were written in a .kv file, the following 2 are written in a .py file

The function it calls is called rst_gmvr and it's is in the gameovereasy screen class and it looks like:

def rst_gmvr(self):
    easy().rec_rst()

This function then calls a function called rec_rst which is in the easy screen class and it looks like:

def rec_rst(self):
    self.ids.easyscore.text = "0"
    sm.current = "easy"

So therefore this function should reset the score counter label called easyscore back to 0 and change the screen to easy. However, it only changes the screen and not the score counter label.

Can someone help me understand how to change both the screen and the score counter label when the button is released.

Thanks :)

By the way, when the button is released no error messages are given. If you need any more information and/or code to answer this I'll be happy to give it to you.

Upvotes: 2

Views: 5545

Answers (1)

Peter Badida
Peter Badida

Reputation: 12199

As you say, you have two functions in two different classes, therefore you need to make the classes see each other. Basically you either need to access one function in another when it's something small, or in your case you'd need another class that would maintain all your classes.

The second option is already there, you just need to type something, because the class is App() which you use for every application. Assign classes easy and gameovereasy to App() and use the call through application via get_running_app() like this:

class My(...):
    def __init__(self, **kwargs):
        self.app = App.get_running_app()
        self.my = self.app.my

class MyAppClass(App):
    my = My()
    def build(self):
        ...

or directly self.my = App.get_running_app().my and then call the function with my.function(). You need add it to every class you want to communicate with.

Upvotes: 1

Related Questions