Update properties of a kivy widget while running code(运行代码时更新 kivy 小部件的属性)
问题描述
我想在运行某些东西时更新 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)
这篇关于运行代码时更新 kivy 小部件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:运行代码时更新 kivy 小部件的属性
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
