【问题标题】:Why do we get the 'TypeError' when running the following code(python, Kivy)?为什么在运行以下代码(python、Kivy)时会出现“TypeError”?
【发布时间】:2018-06-11 14:51:40
【问题描述】:

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

(请参考this Please,如果您需要查看官方文档)

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

在下面的代码 update_bg() 中,该函数用于在其父级(“布局”,Kivy 行话)更改其背景时更新背景(绘制在画布上的矩形)的大小和/或位置位置和/或大小。

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

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

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    答案在docs

    绑定()

    [...]

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

    [...]

    当它读取时,它会将发生变化的对象发送给我们,在本例中为ConversationBox object(self) 和属性的新值。

    一般来说,您应该使用以下内容:

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

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2023-01-05
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多