Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.
In this, we are going to see how can we create a stopwatch using a label.
In the code, we will be creating just a counter using the label in which when you set the time in seconds it will start decreasing like a countdown and in the second we will do the same by using clock object.
Kivy Tutorial – Learn Kivy with Examples.
Clock Object:
- Kivy provides Clock objects.
- Clock objects can be made to call a function when a specified time period has elapsed.
- A clock object in Kivy can be configured to call a function upon every elapse of time duration or only once.
It is good to use kivy inbuilt module while working with clock:
from kivy.clock import Clock
Basic Approach:
1) import kivy
2) import kivyApp
3) import label
4) import Animation
5) Import clock
6) import kivy properties(only needed one)
7) Set minimum version(optional)
8) Create Label class
9) Create App class
10) return Layout/widget/Class(according to requirement)
11) Run an instance of the class
# Simple Approach:
Python3
import kivy
from kivy.app import App
kivy.require( '1.9.0' )
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.properties import StringProperty, NumericProperty
class Clock(Label):
a = NumericProperty( 100 )
def start( self ):
Animation.cancel_all( self )
self .anim = Animation(a = 0 , duration = self .a)
def finish_callback(animation, clock):
clock.text = "FINISHED"
self .anim.bind(on_complete = finish_callback)
self .anim.start( self )
def on_a( self , instance, value):
self .text = str ( round (value, 1 ))
class TimeApp(App):
def build( self ):
clock = Clock()
clock.start()
return clock
if __name__ = = "__main__" :
TimeApp().run()
|
Output:
Note: Countdown starts from 100 and ends on 0
# Now By using Clock Object:
Python3
import kivy
from kivy.app import App
kivy.require( '1.9.0' )
from kivy.uix.label import Label
from kivy.clock import Clock
class ClockDemo(App):
count = 0
def build( self ):
self .myLabel = Label(text = 'Waiting for updates...' )
Clock.schedule_interval( self .Callback_Clock, 1 )
return self .myLabel
def Callback_Clock( self , dt):
self .count = self .count + 1
self .myLabel.text = "Updated % d...times" % self .count
if __name__ = = '__main__' :
ClockDemo().run()
|
Output:
Note: This starts from 0 and runs until you cut the window
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Sep, 2021
Like Article
Save Article