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 func
function 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 小部件的属性


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01