从Kivy Widget类继承对孩子有什么影响?

2024-04-29 10:56:23 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我对OOP的概念不太熟悉,所以这可能只是我不知道的某种形式的python功能。你知道吗

在Kivy中,我们可以通过创建要更改其功能的小部件的子类来修改小部件的行为和外观,例如:

class MyWidget(Button):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        self.size_hint = None
        self.size = 200, 100

然后使用MyWidget:<MyWidget>kv中实例化小部件。如果我希望我的小部件成为根小部件的父级,这是很好的,但是有时这是不需要的,例如当需要一个临时的Popup。你知道吗

在这种情况下,我只需要创建一个典型的类,它在触发事件时被实例化。像这样:

class Interface():
    def __init__(self):    
        btn = Button()
        btn.bind(on_press=self.some_callback)

        self.popup = Popup(content=btn)
        self.popup.open()   

    def some_callback(self, instance):
        print('woo')

这看起来很好,但是小部件事件(on_press这里)不会触发回调函数???bind()函数将调用事件上的回调,因为如果回调函数定义的语法不正确,则会通知我,但由于某些原因,回调的内容不会执行—仅当Interface()Widget()类(Interface(Widget): ...)继承时。 从docs

Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the ‘on_’ callback. If nothing changes, nothing will be done.

btn是小部件,它是Button()的实例,而Widget本身是Widget的子类,它的方法与Interface的父类没有任何连接,那么为什么只有当WidgetInterface的父类时才完全执行回调呢?我错过了什么?你知道吗


Tags: the实例函数selfiniton部件def