简体   繁体   中英

__init__ arguments in Python/Kivy

I'm trying to call an init method, and it's parents in a function. I'm probably doing something obviously dumb, but I can't figure it out. I get an error when I have this code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty, ListProperty
from kivy.clock import Clock
from kivy.graphics import Color

class FieldCommand(Widget):
    def __init__(self, **kwargs):
        super(FieldCommand, self).__init__(**kwargs)
        self.myBoard = Board(col=2, rows=2)
        for c in range(4):
            self.add_widget(Button(text = c))

class Board(Widget):
    def __init__(self, **kwargs):
        super(Board, self).__init__(**kwargs)



class FieldCommandApp(App):
    def build(self):
        return FieldCommand()


if __name__ == '__main__':
    FieldCommandApp().run()

Specifically, my error reads:

File "/Users/.../PycharmProjects/FieldCommand/venv/lib/python3.7/site-packages/kivy/uix/widget.py", line 350, in __init__
     super(Widget, self).__init__(**kwargs)
   File "kivy/_event.pyx", line 243, in kivy._event.EventDispatcher.__init__
 TypeError: object.__init__() takes exactly one argument (the instance to initialize

) I was following the example here :

class Container(BoxLayout):


    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)
        self.previous_text = open(self.kv_file).read()
        parser = Parser(content=self.previous_text)
        widget = Factory.get(parser.root.name)()
        Builder._apply_rule(widget, parser.root, parser.root)
        self.add_widget(widget)

Why is my application getting an error?

Your call to self.myBoard = Board(col=2, rows=2) includes kwargs for col and rows that are passed to the Widget __init__() , which does not accept those kwargs. So the fix is to extract those kwargs in your Board class. You can do that by simply adding Properties in your Board class like this:

class Board(Widget):
    # default values for `row` and `cols`
    col = NumericProperty(1)
    rows = NumericProperty(1)

    def __init__(self, **kwargs):
        super(Board, self).__init__(**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM