Button on_release Action

Date: February 27th 2016
Last updated: February 27th 2016

A button can have 2 states; when the button is clicked and in a down state and when the button is released and returns to a normal state.

A common use for on_release (refer to C in the example below) is to put the focus (or cursor) on a text input box.

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)
        self.random_number.text = str(rand_number)
        self.random_iterator.text = str(self.counter)

    def enter_text(self):
        """
        put cursor in textinput box after 
        releasing the play button
        """
        self.my_text_input.focus = True

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)
    my_text_input: my_text_input #<===== (C)

    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'

        TextInput:
            id: my_text_input #<============ id (C)
            text: 'My text input field...'  


    BoxLayout:
        orientation: 'horizontal'
        size_hint: 1, 0.4

        Button:
            text: 'Play'
            on_press: root.create_random_number() 
            on_release: root.enter_text() #<====== (C)

Output
This is the same example as button on-press multi-action. The difference occurs on releasing the play button. After releasing the play button the cursor goes to a text input field ready for the user to enter text.

onrelease screenshot

Useful resources:

results matching ""

    No results matching ""