Book Image

Kivy Blueprints

Book Image

Kivy Blueprints

Overview of this book

Table of Contents (17 chapters)
Kivy Blueprints
About the Author
About the Reviewers
The Python Ecosystem

Stopwatch controls

Controlling the application by the means of button press events is very easy. All that we need to do for this to work is use the following code:

def start_stop(self):
    self.root.ids.start_stop.text = ('Start'
        if self.sw_started else 'Stop')
    self.sw_started = not self.sw_started

def reset(self):
    if self.sw_started:
        self.root.ids.start_stop.text = 'Start'
        self.sw_started = False
    self.sw_seconds = 0

The first event handler is for the Start and Stop buttons. It changes the state (sw_started) and the button caption. The second handler reverts everything to the initial state.

We also need to add the state property to keep track of whether the stopwatch is running or paused:

class ClockApp(App):
    sw_started = False
    sw_seconds = 0

    def update_clock(self, nap):
        if self.sw_started:
            self.sw_seconds += nap

We change the update_clock function so that it increments sw_seconds only if the stopwatch is started, that is, sw_started is set to True. Initially, the stopwatch isn't started.

In the clock.kv file, we bind these new methods to on_press events:

    id: start_stop
    text: 'Start'
    on_press: app.start_stop()

    id: reset
    text: 'Reset'
    on_press: app.reset()


In Kivy language, we have several context-sensitive references at our disposal. They are as follows:

  • self: This always refers to the current widget;

  • root: This is the outermost widget of a given scope;

  • app: This is the application class instance.

As you can see, implementing event handling for buttons isn't hard at all. At this point, our app provides interaction with the stopwatch, allowing the user to start, stop, and reset it. For the purposes of this tutorial, we're done.