問題描述
我想在運行某些東西時更新 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 小部件的屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!