Python Forum
[Kivy] How do I reference a method in another class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Kivy] How do I reference a method in another class?
#1
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'
Reply
#2
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?
Reply
#3
(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)?
Reply
#4
Solved: I had to pass self.root into ConjugationGame.change_game_state().
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TKinter Widget Attribute and Method Quick Reference zunebuggy 3 786 Oct-15-2023, 05:49 PM
Last Post: zunebuggy
  [PyQt] I get a name Name Error: when calling a method inside a class radoo 2 2,325 Jun-11-2020, 05:02 PM
Last Post: radoo
  [Tkinter] Issue with calling a Class/Method in GUI File Fre3k 3 2,944 Mar-08-2020, 12:35 PM
Last Post: Fre3k
  [Tkinter] Call a class method from another (Tk GUI) class? Marbelous 3 6,133 Jan-15-2020, 06:55 PM
Last Post: Marbelous
  [Tkinter] Class with text widget method AeranicusCascadia 3 7,738 Nov-14-2017, 11:33 PM
Last Post: AeranicusCascadia
  How to define a method in a class 1885 2 4,617 Oct-29-2017, 02:00 AM
Last Post: wavic
  [PyQt] How to put class method into new module? California 0 2,883 Jan-18-2017, 04:05 PM
Last Post: California

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020