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

2022-01-15 00:00:00 python kivy refresh

问题描述

我想在运行某些东西时更新 kivy 小部件的属性...

I want to update the properties of a kivy widget while running something...

例子:

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.

This is gonna show me only the final result of the loop. I'd like to keep updating the label.text while the loop goes.

我寻找了类似 bind()、setter() 和 ask_update() 函数,但如果是这些函数,我不知道如何使用它们.

I looked for something like the bind(), setter() and ask_update() functions, but if are these funcs, I didn't get how to use them.

------------------ 编辑 -----------------------

------------------ EDIT -----------------------

试图适应 inclement 答案(使用时钟在其他线程中运行更新函数),我得到下面的代码试图遵循我的问题的真实想法,但仍然无法正常工作:

Trying to adapt to inclement answer (running the update function in other thread using Clock), I got the code below trying to follow the real idea of my problem, but still not working:

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 函数并使其在 update 函数中命令文本更改时准确地更新标签文本.

I need to call the funcfunction and make it update the label text exactly when I order the text change in update function.


解决方案

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

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)

相关文章