Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kivy Blueprints

You're reading from   Kivy Blueprints Build your very own app-store-ready, multi-touch games and applications with Kivy!

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher Packt
ISBN-13 9781783987849
Length 282 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

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:

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

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

Tip

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.

You have been reading a chapter from
Kivy Blueprints
Published in: Jan 2015
Publisher: Packt
ISBN-13: 9781783987849
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image