【发布时间】:2017-07-20 13:28:35
【问题描述】:
我在 for 循环期间尝试更新标签文本时遇到问题。有类似的条目(例如:Update properties of a kivy widget while running code),但它们似乎并不完全适合我的问题(或者我错过了重点……)。 我运行以下代码:
*.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()
虽然“打印”语句会定期更新 shell,但标签文本仅在 for 循环结束时更新。 谁能向我解释为什么 Kivy 会这样工作以及我如何克服这个问题?
编辑:根据 PM2Ring 和 Gugas,我更改了代码以避免睡眠功能。如果我要求用户在循环继续之前输入一些内容,问题仍然存在。这些值在 shell 中更新,但不在标签上。
【问题讨论】:
-
我不知道 Kivy,但在 GUI 代码中调用
time.sleep通常是个坏主意,因为它会阻塞 一切,因此 GUI 引擎无法获得有机会更新布局。如果您需要延迟,则必须使用 GUI 框架为此目的提供的功能/方法。 -
@PM2Ring 其实是对的,系统很可能会更改标签,并且在被休眠后它不会更新,尝试不使用休眠语句并检查问题是否仍然存在。跨度>
-
@PM2ring, Gugas:我编辑了代码,但问题仍然存在。有什么想法吗?
-
input函数在等待用户输入时阻塞,所以它与调用sleep的效果相同,因此 Kivy 仍然没有机会更新布局。正如我之前所说,我不了解 Kivy,但我认为它具有强制更新布局的功能。 This answer 可能是相关的。 -
你永远不会将
input的结果分配给任何东西,我可以告诉你。
标签: python for-loop label kivy