python – 在运行代码时更新kivy小部件的属性

我想在运行时更新kivy小部件的属性…

例:

class app(App):
    def build(self):
        self.layout = Layout()
        self.name = Label(text = "john")
        self.layout.add_widget(self.name)
        return self.layout

    def update(self):
        for i in range(50): #keep showing the update
            self.name.text = str(i)
            #maybe some sleep here

obj = app()
obj.run()
obj.update()

这只会告诉我循环的最终结果.我想在循环进行时不断更新label.text.

我找了类似bind(),setter()和ask_update()函数的东西,但如果是这些函数,我没有得到如何使用它们.

——————编辑———————–

试图适应恶意答案(使用Clock在其他线程中运行更新功能),我得到了下面的代码,试图按照我的问题的真实想法,但仍然无法正常工作:

class main():
    def __init__(self, app):
        self.app = app

    ... some code goes here ...

    def func(self):
        Clock.schedule_once(partial(self.app.update, self.arg_1, self.arg_2), 0)

class app(App):
    def build(self):
            self.main = main(self)
            self.layout = Layout()
            self.name = Label(text = "john")
            self.layout.add_widget(self.name)
            return self.layout

    ... some code goes here ...

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

obj = app()
obj.run()

当我在更新功能中订购文本更改时,我需要调用func函数并使其更新标签文本.

最佳答案 您需要避免阻止主线程.在大多数情况下,只使用kivy的时钟很方便.您可以执行以下操作.

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)
点赞