【问题标题】:what is in kivy "instance" ? like on_pressed(self, instance, pos)kivy“实例”中有什么?像 on_pressed(self, instance, pos)
【发布时间】:2016-06-15 15:27:31
【问题描述】:

我想知道instance这个词在kivy中是什么意思?

class CustomBtn(Widget):
    pressed = ListProperty([0, 0])

    def on_touch_down(self, touch):
         if self.collide_point(*touch.pos):
             self.pressed = touch.pos
             # we consumed the touch. return False here to propagate
             # the touch further to the children.
             return True
         return super(CustomBtn, self).on_touch_down(touch)

     def on_pressed(self, instance, pos):
         print ('pressed at {pos}'.format(pos=pos))
         print ('My callback is call from', instance)

【问题讨论】:

    标签: kivy kivy-language


    【解决方案1】:

    'instance' 是您按下按钮时对Class CustomBnt 的对象实例的名称和引用。它不必命名为“实例”。您也可以将其称为“obj”或“btn”或任何对您有意义的名称。

    您使用它来收集有关按下按钮的信息。 instance.text 将是按钮上的文本,例如 使用print type(instance) 找出“实例”是什么类型的对象。

    【讨论】:

      【解决方案2】:

      instance 没有特殊含义。此参数用于向方法传达哪个对象触发了事件。考虑一个附加到另一个类的事件的事件处理程序:

      class MyLabel(Label):
          def pressed_handler(self, instance, pos):
              print ('pressed at {pos}'.format(pos=pos))
              print ('My callback is call from', instance)
      
      a = CustomBtn()
      b = MyLabel()
      a.bind(on_pressed=b.pressed_handler)
      

      然后pressed_handler 将通过instance 参数知道哪个对象发送了事件。

      【讨论】:

        猜你喜欢
        • 2021-07-18
        • 1970-01-01
        • 2016-10-02
        • 2016-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-12
        相关资源
        最近更新 更多