简体   繁体   中英

Why do we get the 'TypeError' when running the following code(python, Kivy)?

I am a beginner in python and am trying out Kivy to make GUI. To add a background to a layout, i am trying to follow the example provided in the official documentation.

(Refer this Please, if you need to look at the official documentation)

https://kivy.org/docs/guide/widgets.html#adding-a-background-to-a-layout

In my code below, update_bg(), the function is used to update the size and/or position of the background(a rectangle, drawn on the canvas) whenever its parent(the 'layout', Kivy Jargon) changes its position and/or size.

class ConversationBox(BoxLayout):
  def __init__(self, **kwargs):
      super(ConversationBox, self).__init__(**kwargs)

      beside_message = BoxLayout(orientation='vertical')
      whatever_said = Label(text='Someone said Something', size_hint=(None, None), size=(100, 60))
      remove_button = Button(text='X', size_hint=(None, None), size=(30, 30))
      log = Label(text='Log', size_hint=(None, None), size=(30, 30))

      with self.canvas:
          Color(0, 1, 0, 1)
          self.background = Rectangle(pos_hint=(None, None), size_hint=(None, None), pos=self.pos, size=self.size)
          self.bind(pos=self.update_bg, size=self.update_bg)

      self.add_widget(whatever_said)
      beside_message.add_widget(remove_button)
      beside_message.add_widget(log)
      self.add_widget(beside_message)

  def update_bg(self):  # <----------------This is where the problem is
      self.background.pos = self.pos
      self.background.size = self.size


class test(App):

  def build(self):
      return ConversationBox(orientation='horizontal')


test().run()

When you run this code, you get and error in the console, that is.

TypeError: update_bg() takes 1 positional argument but 3 were given

When you provide two additional arguments, say,

def update_bg(self, arbitrary_arg_1, arbitrary_arg_2):

You don't get any errors. Why does this happen? I have Zero Intuition.

The answer is in the docs :

bind()

[...]

In general, property callbacks are called with 2 arguments (the object and the property's new value) and event callbacks with one argument (the object). The example above illustrates this.

[...]

As it reads, it sends us the object that has the change, in this case the ConversationBox object(self) and the new value of the property.

In general, you should use the following:

def update_bg(self, instance, value):
    self.background.pos = self.pos
    self.background.size = self.size

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