【问题标题】:Variables in Kv language (kivy)Kv 语言 (kivy) 中的变量
【发布时间】:2015-01-31 19:35:35
【问题描述】:

我的 Kivy 语言文件有许多 font_size 属性,都具有相同的值,是否可以在 KV lang 中分配变量? 当前 KV 文件示例:

#User ID
    Label:
        text: 'User ID'
        font_size: 20
        text_size: self.size

    TextInput:
        id: userid
        font_size: 20


    #User PW
    Label:
        text: 'Password'
        font_size: 20
        text_size: self.size

    TextInput:
        id: password
        password: True
        font_size: 20

    Button:
        text: 'Login'
        font_size: 20

可以这样设置吗:

#User ID
    @fs: 20
    Label:
        text: 'User ID'
        font_size: fs
        text_size: self.size

    TextInput:
    id: userid
    font_size: fs


#User PW
Label:
    text: 'Password'
    font_size: fs
    text_size: self.size

TextInput:
    id: password
    password: True
    font_size: fs

Button:
    text: 'Login'
    font_size: fs

通过这样做,我只需更改 FS 变量值就可以立即更改字体大小,此外,类似的解决方案可能会帮助我更快地创建基于主题的文件。谢谢。

【问题讨论】:

    标签: kivy


    【解决方案1】:

    我只能通过更改 FS 变量值来一次更改字体大小,

    您可以使用#:set name value 设置一个值,但这并不是您想要的。由于您希望变量更新,您应该使用 kivy 属性,以便事件系统为您处理它。

    在这种情况下,由于您希望很多不同的东西都依赖于这样的大小,因此您可以使用应用类的属性。

    class YourApp(App):
        font_size = NumericProperty(20)
    

    然后在 kv 中

    font_size: app.font_size
    

    对 App 实例的 font_size 的任何更改都会自动传播到这些 kv 规则。

    【讨论】:

    • 跟进,font_size可以继承自父widget吗?如果多个文本或标签小部件嵌套在一个网格中,我可以在网格上设置 font_size 吗?
    • 您可以通过为每个小部件添加一个规则,如上面的答案(除了为每个小部件使用 id 和 font_size: id_name.font_size)来显式继承,或者在绑定到的新类中抽象此行为它的父级不是 font_size。
    • NumericPropertyint有什么区别?
    【解决方案2】:

    是的,有办法。你要找的是这个表达式:

    #:set name value
    

    可以查看文档here

    您的 .kv 文件:

    #User ID
        #:fs 20
        Label:
            text: 'User ID'
            font_size: fs
            text_size: self.size
    
        TextInput:
        id: userid
        font_size: fs
    
    
    #User PW
    Label:
        text: 'Password'
        font_size: fs
        text_size: self.size
    
    TextInput:
        id: password
        password: True
        font_size: fs
    
    Button:
        text: 'Login'
        font_size: fs
    

    【讨论】:

    • 你的 kv 文件示例应该是 #:set fs 20
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多