Update properties of a kivy widget while running code

﹥>﹥吖頭↗ 提交于 2019-12-05 12:31:36

You need to avoid blocking the main thread. In most cases, it's convenient to just use kivy's clock. You can do something like the following.

from kivy.clock import Clock

class app(App):
    def build(self):
        self.layout = Layout()
        self.name = Label(text = "john")
        self.layout.add_widget(self.name)
        self.current_i = 0
        Clock.schedule_interval(self.update, 1)
        return self.layout

    def update(self, *args):
        self.name.text = str(self.current_i)
        self.current_i += 1
        if self.current_i >= 50:
            Clock.unschedule(self.update)

Not sure if anyone still needs the answer, but it seems that your mistake is here:

def update(self, dt, arg_1, arg_2):
    self.name = arg_1
    sleep(5)
    self.name = arg_2

You either assign arg1 and arg2, presumably strings, to the widget, which doesn't seem to make much sense. Or creating a new widget and reassigning it to the same variable, which is also not correct. Instead you can assign to property directly:

def update(self, dt, arg_1, arg_2):
    self.name.text = arg_1
    sleep(5)
    self.name.text = arg_2

Or you can create a StringProperty on your main object and bind self.name.text to it, but I personally prefer updating the screen manually. Explicit is better than implicit and all that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!