我嘗試在for循環中更新標籤文本時出現問題。有類似的條目(例如:Update properties of a kivy widget while running code),但它們似乎並不完全符合我的問題(或者我錯過了這一點...)。 我運行下面的代碼:Kivy:標籤文本在for循環中不更新
*的.py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
#from time import sleep
class MyBox(BoxLayout):
tobeupd = StringProperty()
def __init__(self,*args,**kwargs):
super(MyBox,self).__init__(*args,**kwargs)
self.tobeupd = '#'
def upd_ltxt(self):
for i in range(1,10):
self.tobeupd = str(i)
print(self.tobeupd)
input('Write something: ') # new line, see edit below
#sleep(0.5)
class updApp(App):
def build(self):
return MyBox()
if __name__ == '__main__':
updApp().run()
* .kv
<MyBox>:
orientation: 'horizontal'
cols: 2
Label:
text: root.tobeupd
Button:
text: 'Start Update'
on_release: root.upd_ltxt()
儘管 '印刷' 在聲明的最後定期更新的外殼,標籤文字更新僅for循環。 任何人都可以向我解釋爲什麼Kivy以這種方式工作,以及我如何克服這個問題?
編輯:根據PM2Ring和Gugas,我改變了代碼,以避免睡眠功能。如果我要求用戶在繼續循環之前輸入內容,問題依然存在。值在shell中更新,但不在標籤上。
我不知道Kivy,但在GUI代碼中調用'time.sleep'通常是個壞主意,因爲它會阻塞_everything_,所以GUI引擎沒有機會更新佈局。如果您需要延遲,您必須使用GUI框架爲此提供的功能/方法。 –
@ PM2Ring實際上是正確的,系統可能會更改標籤,並在被睡眠打中後不會更新,嘗試沒有睡眠聲明並檢查問題是否仍然存在。 –
@ PM2ring,Gugas:我編輯了代碼,但問題依然存在。任何想法? – dade100