您的代碼創建兩個不同的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'
編輯:爲了延緩標籤文本屬性的變化,使用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)
謝謝這真的有用,它的工作原理。然而,它在圖形用戶面已經加載之前改變標籤的文本,並且當我到達屏幕時它已經改變了文本。我怎樣才能在實際屏幕上改變文字? –
啊,是的。這是因爲'time.sleep(5)'。在Kivy中,這會凍結你的應用程序。如果您可以安排某個事件,則應該使用「時鐘」。 – ODiogoSilva
我試過這個解決方案,並添加了'Clock.schedule_once(lambda x:update_label(a,「50」),5)',然後是另一個'Clock.schedule_once(lambda x:update_label (a,「40」),5)'。然而,這只是跳過第一行,直接顯示40.我將如何解決這個問題。這非常有用。 –