如何更新标签中的文字?
a=Label(text='60')
self.add_widget(a)
在代码运行时如何将60更改为另一个数字,例如50。
我试图改变这样的文字:
a=Label(text='60')
self.add_widget(a)
time.sleep(5)
a=Label(text='50')
self.add_widget(a)
但这似乎不起作用。
答案 0 :(得分:0)
您的代码会创建两个不同的Label小部件,并将它们添加到小部件树中。如果要更改先前创建的窗口小部件的特定属性:
# Create Label and reference it to var 'a'
a = Label(text='60')
self.add_widget(a)
time.sleep(5)
# You can use the 'a' var to access the previously created Label
# and modify the text attribute
a.text = '50'
编辑:为了延迟更改Label文本属性,请使用Clock
代替time
(最后一个会在计时器结束时冻结您的应用)
from kivy.clock import Clock
def update_label(label_widget, txt):
label_widget.text = txt
# Create Label and reference it to var 'a'
a = Label(text='60')
self.add_widget(a)
# In five seconds, the update_label function will be called
# changing the text property of the 'a' Label to "50"
Clock.schedule_once(lambda x: update_label(a, "50"), 5)
EDIT2:带倒计时的标签
要定期更改标签,您可以使用Clock.schedule_interval
from kivy.clock import Clock
def countdown(label_widget):
# Convert label text to int. Make sure the first value
# is always compliant
num = int(label_widget.text)
# If the counter has not reach 0, continue the countdown
if num >= 0:
label_widget.text = str(num - 1)
# Countdown reached 0, unschedulle this function using the
# 'c' variable as a reference
else:
Clock.unschedule(c)
# Create Label and reference it to var 'a'
a = Label(text='60')
self.add_widget(a)
# Every 1 second, call countdown with the Label instance
# provided as an argument
c = Clock.schedule_interval(lambda x: countdown(a), 1)