【问题标题】:Understanding Kivy properities and binding methods了解 Kivy 属性和绑定方法
【发布时间】:2016-06-20 10:57:15
【问题描述】:

我在理解自定义属性的使用以及将方法绑定到事件的方式方面遇到问题。 这是我的代码:

from kivy.app import App
from kivy.lang import Builder

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import StringProperty

kivy_lang = '''
<MainWidget>:
    on_my_property: my_label.text = 'from button bind method via StringProperty' + my_property

    Label:
        id: my_label
        text: root.my_property
    Button:
        id: my_button
        text: 'intro button'

'''


class MainWidget(BoxLayout):
    # bind some properties
    my_property = StringProperty('0')

    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)
    #     if needed to do sth on widget construction
        self.ids.my_button.bind(on_press=self.my_method)


    def my_method(self,*args,**kwargs):
        self.my_property = str(int(self.my_property)+1)
        self.ids.my_button.text = 'new'


class MyApp(App):
    def build(self):
        Builder.load_string(kivy_lang)
        return MainWidget()

if __name__ == '__main__':
    MyApp().run()

当我运行它时,它呈现正常,但是当我单击一个按钮时,结果我得到 NameError: name 'my_property' 未定义

我尝试使用 kv lang 中的 Button 绑定方法(并在 python 端删除整个 'init()'):

on_press: root.my_method

然后当我按下按钮时,应用程序不会崩溃,但什么也没发生

有人可以解释一下如何调整此代码以使其正常工作吗? 我知道代码有点“混合技术”,但我这样做是为了了解不同的方法,所以如果你不把它全部转过来,我将不胜感激:)

【问题讨论】:

    标签: python properties bind kivy


    【解决方案1】:

    1/您在“on_my_property”绑定中的“my_property”之前缺少“self”,因此崩溃

    2/ 在 kv 绑定中。 python代码调用写成,所以root.my_method后面需要有'()',否则语句无效。

    【讨论】:

    • 很好,感谢您的快速回复 - 看起来我毕竟不是那么远 :) 所以我需要记住:1) & 2) - 在 kv lang 中写在 ':' 之后的内容是'在任何时候都不是真正的绑定,当属性更新时,它总是一个 python 代码来执行'原样'(因此需要'self.'来引用当前小部件实例中的属性/属性)
    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多