Python Forum
[Kivy] How do I reference a method in another class? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Kivy] How do I reference a method in another class? (/thread-24715.html)



How do I reference a method in another class? - Exsul1 - Feb-29-2020

How do I reference a method in my BoxLayout class from my App class?

class ConjugationGame(BoxLayout):
    round = 1
    game_state = 0
    def change_game_state(self):
        if self.game_state > 4:
            self.game_state == 1
        else:
            self.game_state += 1


class ConjugationApp(App):
    def build(self):
        Window.bind(on_key_down=self.key_down)
        return ConjugationGame()

    def key_down(self, key, scancode=None, *_):
        if scancode == 281:  # PAGE_DOWN
            print("PAGE_DOWN pressed")
            ConjugationGame.change_game_state()
When I press Page Down, I get this error:

Quote:TypeError: change_game_state() missing 1 required positional argument: 'self'



RE: How do I reference a method in another class? - ndc85430 - Feb-29-2020

On line 18, you need to call the method on an instance of the ConjugationGame class. You could of course just add the parens to that line to call ConjugationGame's __init__, but obviously then you'd be creating a new instance on every call of key_down. Is that what you want?


RE: How do I reference a method in another class? - Exsul1 - Feb-29-2020

(Feb-29-2020, 08:00 PM)ndc85430 Wrote: On line 18, you need to call the method on an instance of the ConjugationGame class. You could of course just add the parens to that line to call ConjugationGame's __init__, but obviously then you'd be creating a new instance on every call of key_down. Is that what you want?

I don't think that's what I want, but I'm not entirely sure how this all works. Is the App class creating an instance of the BoxLayout class when it returns it in the build method? If so, can I just create a variable in the general namespace and return that variable instead (for the purposes of calling a method on it)?


RE: How do I reference a method in another class? - Exsul1 - Mar-02-2020

Solved: I had to pass self.root into ConjugationGame.change_game_state().