Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Create a stopwatch using clock object in kivy using .kv...

Python | Create a stopwatch using clock object in kivy using .kv file

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.

Kivy Tutorial – Learn Kivy with Examples.

Clock Object: 

The Clock object allows you to schedule a function call in the future; once or repeatedly at specified intervals. 
You can get the time elapsed between the scheduling and the calling of the callback via the dt argument:

Python3




# define callback
def my_callback(dt):
    pass
 
 
# clock.schedule_interval with time specified
Clock.schedule_interval(my_callback, 0.5)
 
# clock.schedule_once with time specified
Clock.schedule_once(my_callback, 5)
 
# call my_callback as soon as possible.
Clock.schedule_once(my_callback)


Note: If the callback returns False, the schedule will be canceled and won’t repeat. 
 

In this, we are going to create the kivy the stopwatch and we are creating 3 buttons in this which are the start, pause, resume.
 

It is good to use kivy inbuilt module while working with clock and: 
from kivy.clock import Clock

 

Basic Approach:  
1) import kivy
2) import kivyApp
3) import Builder
4) import Boxlayout
5) Import clock
6) import kivy properties(only needed one)
7) Set minimum version(optional)
8) Create the .kv code:
     1) Create Buttons
     2) Add call to button
     3) Add label 
9) Create Layout class
10) Create App class
11) return Layout/widget/Class(according to requirement)
12) Run an instance of the class

# Implementation of the Approach: 
 

Python3




'''
Code of How to create Stopwatch
'''
    
# Program to Show how to create a switch
# import kivy module   
import kivy 
        
# base Class of your App inherits from the App class.   
# app:always refers to the instance of your application  
from kivy.app import App
      
# this restrict the kivy version i.e 
# below this kivy version you cannot 
# use the app or software 
kivy.require('1.9.0')
  
# The Builder is responsible for creating
# a Parser for parsing a kv file
from kivy.lang import Builder
 
# The Properties classes are used
# when you create an EventDispatcher.
from kivy.properties import NumericProperty
 
# BoxLayout arranges children in a vertical or horizontal box.
# or help to put the children at the desired location.
from kivy.uix.boxlayout import BoxLayout
 
# he Clock object allows you to
# schedule a function call in the future
from kivy.clock import Clock
 
 
# Create the .kv file and load it by using Builder
Builder.load_string('''
 
<MainWidget>:
 
    # Assigning the alignment to buttons
    BoxLayout:
        orientation: 'vertical'
 
        # Create Button
         
        Button:
            text: 'start'
            on_press: root.start()
             
        Button:
            text: 'stop'
            on_press: root.stop()
             
        Button:
            text: 'Reset'
            on_press: root.number = 0
 
    # Create the Label
    Label:
        text: str(round(root.number))
        text_size: self.size
        halign: 'center'
        valign: 'middle'
''')
  
# Create the Layout class
class MainWidget(BoxLayout):
     
    number = NumericProperty()
     
    def __init__(self, **kwargs):
 
        # The super() builtin
        # returns a proxy object that
        # allows you to refer parent class by 'super'.
        super(MainWidget, self).__init__(**kwargs)
 
        # Create the clock and increment the time by .1 ie 1 second.
        Clock.schedule_interval(self.increment_time, .1)
 
        self.increment_time(0)
 
    # To increase the time / count
    def increment_time(self, interval):
        self.number += .1
 
    # To start the count
    def start(self):
         
        Clock.unschedule(self.increment_time)
        Clock.schedule_interval(self.increment_time, .1)
 
    # To stop the count / time
    def stop(self):
        Clock.unschedule(self.increment_time)
 
# Create the App class
class TimeApp(App):
    def build(self):
        return MainWidget()
 
# Run the App
TimeApp().run()


Output: 

Note: 

In this when you press start count start, when press Restart it starts again and when pause it get paused.

Code Explanation:

  1. The code starts by importing the kivy module.
  2. The code then creates a new class called Stopwatch and extends from the App class.
  3. Next, it sets up an instance of your application with app:always set to true.
  4. Then it restricts the kivy version i.e below this kivy version you cannot use the app or software .
  5. The next line is where we create our stopwatch object which has two methods on it: start() and stop().
  6. The code is a program that shows how to create a switch.
  7. The code starts by importing the kivy module.
  8. It then proceeds to define the base class of your app as App and then restricts the kivy version i.e below this kivy version you cannot use the app or software.
  9. The code starts with a class called Builder.
  10. The Builder is responsible for creating a Parser for parsing a kv file.
  11. The Properties classes are used when you create an EventDispatcher.
  12. BoxLayout arranges children in a vertical or horizontal box, or help to put the children at the desired location.
  13. The code will create a new Builder object.
  14. The code then creates a Parser class, which is used to parse the kv file.
  15. Lastly, it creates an EventDispatcher class, which is used to dispatch events from the parser.
  16. The code starts by creating a BoxLayout object and assigning it the orientation of ‘vertical’.
  17. Then, two buttons are created.
  18. The first button has text “start” and is assigned to on_press: root.start().
  19. The second button has text “stop” and is assigned to on_press: root.stop().
  20. Finally, a Label with the text “Reset” is created and given an on_press event handler that calls root.number = 0.
  21. The code starts by creating a BoxLayout object and assigning it the orientation of ‘vertical’.
  22. Then, two buttons are created.
  23. The first button has text “start” and is assigned to on_press: root.start().
  24. The second button has text “stop” and is assigned to on_press: root.stop().
  25. Finally, a Label with the text “Reset” is created and given an on_press event handler that calls root.number = 0
  26. The code is a snippet of code that creates a button layout.
  27. The Button object has an on_press method which will be called when the button is pressed.
  28. The Label object has an on_text method which will be called when the label is clicked.
  29. The code starts by creating a class called MainWidget.
  30. This is the parent class of all widgets in this program.
  31. The code then creates an instance variable called number and initializes it to NumericProperty().
  32. The next line of code creates a function that will be used to create the layout for each widget in this program.
  33. It takes two arguments: self, which refers to the current object, and **kwargs, which are passed into the constructor as keyword arguments.
  34. The super() builtin returns a proxy object that allows you to refer parent classes by ‘super’.
  35. In other words, when we call super(MainWidget), it calls our own __init__ method with whatever parameters were passed into super(), but also passes on any additional parameters from kwargs (which is why there’s no comma after **kwargs).
  36. Next comes some boilerplate code before finally getting down to business with analyzing what happens when we run this code: self = MainWidget(**kwargs) self._number = str(round(root.number)) self._text_size = self.size self._halign = ‘center’ self._valign = ‘middle’
  37. The code is a snippet of code that creates the layout class MainWidget.
  38. The code also creates a property number and then defines the __init__ method.
  39. The super() builtin returns a proxy object that allows you to refer parent class by ‘super’.
RELATED ARTICLES

Most Popular

Recent Comments