为什么在运行以下代码(python,Kivy)时会出现'TypeError'?

时间:2018-06-11 06:34:48

标签: python kivy

我是python的初学者,我正在尝试Kivy制作GUI。 要为布局添加背景,我试图按照官方文档中提供的示例。

(如果您需要查看官方文档,请参阅此请

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

在我的代码update_bg()中,该函数用于更新背景(在画布上绘制的矩形)的大小和/或位置,只要其父级('layout',Kivy Jargon)更改其位置和/或大小。

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()

当您运行此代码时,您会在控制台中获得错误,即。

TypeError:update_bg()需要1个位置参数但是3个被赋予

当您提供另外两个参数时,例如

def update_bg(self, arbitrary_arg_1, arbitrary_arg_2):

您没有收到任何错误。 为什么会这样? 我有零直觉。

1 个答案:

答案 0 :(得分:1)

答案在docs

  

<强> bind()的

     

[...]

     

通常,使用 2个参数(对象)调用属性回调   和属性的新值)和带有一个参数的事件回调   (物体)。上面的例子说明了这一点。

     

[...]

在读取时,它会向我们发送包含更改的对象,在本例中为ConversationBox对象(self)和属性的新值。

通常,您应该使用以下内容:

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