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

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.

主站蜘蛛池模板: 林州市| 宣武区| 邻水| 鄂温| 团风县| 塘沽区| 长泰县| 商南县| 和林格尔县| 阿鲁科尔沁旗| 贺兰县| 杭锦后旗| 马山县| 静宁县| 绥芬河市| 梓潼县| 景宁| 宝清县| 双鸭山市| 淮阳县| 喜德县| 天柱县| 定结县| 靖州| 融水| 阜康市| 佛学| 离岛区| 离岛区| 玛曲县| 岳池县| 宾阳县| 沂源县| 延边| 昭觉县| 尼木县| 日照市| 葫芦岛市| 汽车| 田东县| 梨树县|