Button Onpress Action
Date: February 26th 2016
Last updated: February 26th 2016
You can define functions inside a class that can be called from the kv file. The functions are defined using the stock standard python language. The only difference being that the class have inherited from Boxlayout.
import kivy kivy.require('1.9.1') from kivy.app import App from kivy.uix.boxlayout import BoxLayout import random class Sample(BoxLayout): def create_random_number(self): """Returns a random number between 1 and 100""" rand_number = random.randrange(1,100,1) # Label only accepts string format: use str(object) self.random_number.text = str(rand_number) # You don't have to return a value for this to work class SampleApp(App): def build(self): return Sample() if __name__ == '__main__': SampleApp().run()
#:kivy 1.9.1 <Sample>: orientation: 'vertical' random_number: random_number #<==== global id BoxLayout: orientation: 'vertical' Label: #<================== Label to change on click id: random_number #<======== id matching above text: 'Test label at V1 position' font_size: '40sp' ToggleButton: text: 'Test ToggleButton at V2 position' 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 Button: text: 'Reset' Button: text: 'Quit'
Note the play button is in the clicked state and appears blue. Each time play is pressed the Label in the V1 position (top box) is updated to have a new random number.