官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 文登市| 汕头市| 林西县| 申扎县| 平江县| 密山市| 丁青县| 丰顺县| 柳河县| 平南县| 绍兴县| 萨嘎县| 桐城市| 榆林市| 荆州市| 石嘴山市| 灌云县| 宜兰市| 诸暨市| 海盐县| 攀枝花市| 二连浩特市| 钟山县| 伊金霍洛旗| 布拖县| 射阳县| 长春市| 建瓯市| 明溪县| 百色市| 珠海市| 即墨市| 开封县| 磐石市| 清水县| 云龙县| 堆龙德庆县| 吴堡县| 宁明县| 合水县| 铜梁县|