Kivy Course #5 – Properties and Clock Definitions
- July 4, 2015
At the fifth part of Kivy course, properties and Clock are introduced and an example counter application is made. This application counts with seconds and have abilities to start, pause and reset the timer.
At the first stage the Python file is:
#-*-coding:utf-8-*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.clock import Clock
class RootWidget(BoxLayout):
counter = NumericProperty(0)
def on_counter(self, a, b):
print "degismis"
def startCounter(self):
Clock.schedule_interval(self.saniyeGuncelle, 1)
return "Started"
def pauseCounter(self):
Clock.unschedule(self.saniyeGuncelle)
return "Paused"
def resetCounter(self):
self.saniyeSifirla()
return "Stopped"
def saniyeGuncelle(self, dt):
print self.counter
self.counter += 1
def saniyeSifirla(self):
self.counter = 0
class etiketApp(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
etiketApp().run()
And the Kivy file which should be named as etiket.kv is:
<RootWidget>:
orientation: "vertical"
Label:
id: hello_text
text: str(root.counter)
font_size: "50sp"
Label:
id: my_text
text: "İkinci yazı"
Button:
text: "Baslat"
on_press: my_text.text = root.startCounter()
Button:
text: "Pause"
on_press: my_text.text = root.pauseCounter()
Button:
text: "Reset"
on_press: my_text.text = root.resetCounter()
At this stage, when user presses to start multiple times, it schedules more than one intervals and this causes the counter app to count wrong. To fix this, a new Python code is implemented as follows:
#-*-coding:utf-8-*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.clock import Clock
class RootWidget(BoxLayout):
counter = NumericProperty(0)
counting = False
def on_counter(self, a, b):
print "degismis"
def startCounter(self):
if not self.counting:
Clock.schedule_interval(self.saniyeGuncelle, 1)
self.counting = True
return "Started"
else:
return "Already started"
def pauseCounter(self):
Clock.unschedule(self.saniyeGuncelle)
self.counting = False
return "Paused"
def resetCounter(self):
self.saniyeSifirla()
return "Stopped"
def saniyeGuncelle(self, dt):
print self.counter
self.counter += 1
def saniyeSifirla(self):
self.counter = 0
class etiketApp(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
App = etiketApp()
App.run()
At this point, the Kivy file stayed the same and the name of it stayed the same, too.