Kivy:事务

时间:2016-02-04 16:32:42

标签: python properties transactions kivy

假设我从Button继承,添加了一个额外的属性:

class MyButton(Button):
    value = ObjectProperty(None)

进一步假设value和按钮的text属性总是一起更改,比如说方法

def update_data(self, data):
    self.text = data[0]
    self.value = data[1]

现在,如果我有一个绑定到text的回调,它就无法访问新的value。有没有办法延迟触发事件直到update_data方法结束(以便合并对象的状态,如数据库事务)?只是绑定到value是不可靠的,如果不熟悉实现的人改变了另一种方法中属性赋值的顺序呢?

1 个答案:

答案 0 :(得分:1)

您的on_text方法可以使用Clock.schedule_once(callback, 0)安排另一种方法尽快调用。一个例子:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.clock import Clock

Builder.load_string("""
<MyWidget>:
    my_button: my_button
    MyButton
        text: "..."
        id: my_button
    Button
        text: "value_text_order"
        on_press: root.value_text_order()
    Button
        text: "text_value_order"
        on_press: root.text_value_order()
""")

class MyButton(Button):
    value = ObjectProperty(None)
    my_button = ObjectProperty()

    def on_text(self, instance, value):
        Clock.schedule_once(self.on_test_and_value, 0)

    def on_test_and_value(self, *args):
        print("text:{} value: {}".format(self.text, self.value))

class MyWidget(BoxLayout):
    def value_text_order(self, *args):
        self.my_button.value = 'b'
        self.my_button.text = 'a'

    def text_value_order(self, *args):
        self.my_button.text = 'c'
        self.my_button.value = 'd'

class MyApp(App):
    def build(self):
        return MyWidget()

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