Kivy 自定义小部件行为

Kivy custom widget behaviour

我是编程新手,刚接触 Kivy 学习。我遇到了一些奇怪的事情,所以创建了这个小例子来演示。

在我的 text.kv 文件中我有这个:

#:kivy 2.0.0

<smallLabel@Label>:
    font_size: 40

<bigLabel@Label>:
    font_size: 60

BoxLayout:
    orientation:'vertical'
    padding: 20
    spacing: 5
    
    smallLabel:
        text: 'Stays the same'

    bigLabel:
        id: changes
        text: 'changes'

在我的 python 文件中:

from kivy.app import App


class TestApp(App):
    pass

if __name__ == "__main__":
    TestApp().run()

当我 运行 我得到这个:

File "/home/marty/Python/datatut/test.kv", line 15
     text: 'Stays the same'
         ^
 SyntaxError: invalid syntax

现在,如果我更改小部件的大小写,使第一个字母大写,它就可以工作了:

<SmallLabel@Label>:
    font_size: 40

<bigLabel@Label>:
    font_size: 60

BoxLayout:
    orientation:'vertical'
    padding: 20
    spacing: 5
    
    SmallLabel:
        text: 'Stays the same'

    bigLabel:
        id: changes
        text: 'changes'

请注意,我只更改了 SmallLabel。我将 bigLable 保留为小写。 如果我反过来做,那就是留下 smallLabel 但制作 BigLabel 它失败并出现相同的错误。 为什么我需要将我的小部件的名称大写,为什么只有第一个? 我确实在所有示例中注意到,我看到自定义小部件名称的第一个字母始终大写,但没有看到这是一项要求,如果是,那么为什么第二个小部件在第一个小部件的情况下起作用是大写的吗?

KV 语言加载器需要能够区分小部件和子小部件的属性,如您所见,这两种只是以 : 结尾的一行文本,但是有一个技巧,假设您的 classes 遵循大写 classes 和 snake_case 属性的 PEP8 约定,它能够正确猜测。

这是https://kivy.org/doc/stable/guide/lang.html#instantiate-children中指出的(我有点同意)

Note

Widget names should start with upper case letters while property names should start with lower case ones. Following the PEP8 Naming Conventions is encouraged.

我假设第二个不需要这个猜测,因为它在第一个块之后没有缩进,所以它不能是父 class 的属性(属性必须在子声明之前),所以它只能是一个子部件,在这种情况下不需要这个规则,但我无法从 quick glance at the code

中找到这是怎么发生的