当我尝试在 for 循环期间更新标签文本时遇到问题。还有类似的条目(例如:运行代码时更新 kivy 小部件的属性)但它们似乎并不完全符合我的问题(或者我错过了重点......)。
我运行以下代码:
*.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()
虽然“print”语句定期更新 shell,但标签文本仅在 for 循环结束时更新。
谁能向我解释为什么 Kivy 会这样工作以及我如何克服这个问题?
编辑:根据 PM2Ring 和 Gugas,我更改了代码以避免睡眠功能。如果我要求用户在继续循环之前输入一些内容,问题仍然存在。这些值在 shell 中更新,但不在标签上更新。
您可以使用threading
为了这。
当您在 kivy 中执行循环或等待输入时,主线程正在等待,并且应用程序上不会更新任何内容。threading
会阻止这种情况发生。
Use threading
除了主线程之外创建另一个线程。
例子:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.lang import Builder
import threading
Builder.load_string('''
<MyBox>:
orientation: 'horizontal'
cols: 2
Label:
text: root.tobeupd
Button:
text: 'Start Update'
on_release: root.upd_ltxt()
''')
class MyBox(BoxLayout):
tobeupd = StringProperty()
def __init__(self,*args,**kwargs):
super(MyBox,self).__init__(*args,**kwargs)
self.tobeupd = '#'
def upd_ltxt(self):
threading.Thread(target=self.update_label).start()
def update_label(self):
for i in range(1,10):
print(self.tobeupd)
self.tobeupd = str(i)
input('Write something: ') # new line, see edit below
class updApp(App):
def build(self):
return MyBox()
if __name__ == '__main__':
updApp().run()
现在值得一提的是,即使第一个线程尚未完成,您也可以继续按下按钮并启动线程。这可能是一种不需要的行为。
可以通过在线程开头禁用按钮并在结束时再次启用它来防止这种情况。
为按钮指定一个以 kv 为单位的 id:
Button:
id: updatebutton
text: 'Start Update'
on_release: root.upd_ltxt()
并在线程中这样做:
def update_label(self):
self.ids.updatebutton.disabled = True
for i in range(1,10):
self.tobeupd = str(i)
input('Write something: ')
self.ids.updatebutton.disabled = False
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)