【发布时间】:2019-06-25 09:41:05
【问题描述】:
我有一个倒计时计时器,它从 randint() 参数给定范围内的随机整数开始,倒计时到零。目的是使计时器在第一次达到零时以新的随机数重新启动(即圈功能),并在第二次达到零时显示“FINISH”。
这是我第一次使用 kivy,如果解决方案很明显,请见谅。目前我只需要两次迭代,但我可能需要稍后调整它,以便计时器在最终停止之前可以运行任意次数。圈数将在运行应用程序之前在代码中确定,而不是由应用程序用户在运行应用程序时确定。
from kivy.app import App
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.properties import NumericProperty
from random import randint
class IncrediblyCrudeClock(Label):
for i in range(2):
r=randint(3,7)
a = NumericProperty(r) # Number of seconds to countdown
def start(self): #Function to initiate the countdown
Animation.cancel_all(self) # stop any current animations
self.anim = Animation(a=0, duration=self.a) #a=0 sets the
#final destination of a. duration sets the time taken to reach stopping
#point (i.e 5 seconds for a=5)
def finish_callback(animation, incr_crude_clock):
if self.i==1:
incr_crude_clock.text = "FINISHED" #when the clock
#reaches zero, display "FINISHED"
self.anim.bind(on_complete=finish_callback) #call the
#finish_callback function once a=0
self.anim.start(self) #Start the animation (otherwise clock
#stuck at 5 for a=5)
class TimeApp(App):
def build(self):
crudeclock = IncrediblyCrudeClock()
crudeclock.start()
return crudeclock
if __name__ == "__main__":
TimeApp().run()
<IncrediblyCrudeClock>
text: str(round(self.a, 1))
应用在第一次倒计时时确实按预期运行。选择一个随机数,计时器倒计时至零,但在第一次倒计时后它会停止并显示“已完成”。似乎 for 循环在应用程序实际启动之前从零迭代到一,因此,当倒计时开始时, i 已经等于 1(而不是先从 a 运行到零,并且 i=0 和然后在 i=1 的情况下从新的 a 到零)。我想这是因为 for 循环在错误的位置(即不是在调用 start 函数时),但我一直无法弄清楚如何纠正这个问题。 这也是我第一次使用堆栈溢出,所以如果您需要了解其他信息,请告诉我。
【问题讨论】:
标签: python timer kivy kivy-language