Button onpress Multi-action

Date: February 26th 2016
Last updated: February 26th 2016

A button can do multiple things even if its called once. In this example I update 2 labels; the random number and a count of the number fo times the button was pressed. I am still using one function called "create_random_number()", but I am now updating two text strings.

main.py

import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import random

class Sample(BoxLayout):
    def __init__(self, **kwargs):
        super(Sample, self).__init__(**kwargs)
        # record the number of button presses
        self.counter = 0 

    def create_random_number(self):
        """
        Returns a random number between 1 and 100.
        Also changes the iterator display.
        """
        self.counter += 1
        rand_number = random.randrange(1,100,1)
        # Label only accepts string format: use str(object)
        self.random_number.text = str(rand_number)
        self.random_iterator.text = str(self.counter)

class SampleApp(App):
    def build(self):
        return Sample()

if __name__ == '__main__':
    SampleApp().run()

sample.kv

#:kivy 1.9.1
<Sample>:
    orientation: 'vertical'
    random_number: random_number #<==== (A)
    random_iterator: random_iterator #<==== (B)

    BoxLayout:
        orientation: 'vertical'
        Label:  
            id: random_number #<======== id (A)
            text: 'Test label at V1 position'
            font_size: '40sp'  

        Label:
            id: random_iterator #<====== id (B)
            text: 'Test ToggleButton at V2 position'
            font_size: '40sp'

    BoxLayout:
        orientation: 'horizontal'
        size_hint: 1, 0.4
        Button:
            text: 'Play'
            # on_press uses the function created in main.py
            on_press: root.create_random_number() # action(A and B) 
        Button:
            text: 'Reset'
        Button:
            text: 'Quit'

Output
The play button is in the "down" state so it is blue in this image. The top number is the random number, and the second number is the number of times the play button has been pressed. Reset and Quit buttons do nothing.

onpress multi-action screenshot

results matching ""

    No results matching ""