How do I create a button with Kivy?

I am hoping to eventually create a button to pause/start/end a pong app I built as a learning exercise. However, to understand the basics of how to create a button in the first place, and assign a response to it I am just wanting to create a button that notifies me every time the button state changes. Here is the python code I have so far:

import kivy.uix.button as kb
from kivy.app import App
from kivy.uix.widget import Widget

class Button_Widget(Widget):
    def callback(instance, value):
        print('The button <%s> state is <%s>' % (instance, value))

    btn1 = kb.Button(text='Hello World 1')
    btn1.bind(on_press=callback)

class ButtonApp(App):
    def build(self):
        button = Button_Widget()
        return button

with the associated kv file:

#:kivy 1.0.9

<Button_Widget>:
    size: 100, 100
    canvas:
        Rectangle:
            pos = self.pos
            size = self.size

So far the only resources I have found are these (1 and 2) Kivy turorials, which aren't too helpful. Or at least, I don't understand their language enough yet for them to be useful

1 answer

  • answered 2018-07-11 14:16 ikolim

    Solution

    In the class Button_Widget(), you have to override the constructor, __init__() so that you can add the button widget to the root widget. Please refer to the example for details.

    References

    Programming Guide » Kivy Basics » Create an application

    Programming Guide » Kv language

    Kivy Language

    Event dispatcher » bind() Bind an event type or a property to a callback.

    Example

    main.py

    import kivy.uix.button as kb
    from kivy.app import App
    from kivy.uix.widget import Widget
    
    
    class Button_Widget(Widget):
    
        def __init__(self, **kwargs):
            super(Button_Widget, self).__init__(**kwargs)
            btn1 = kb.Button(text='Hello World 1')
            btn1.bind(on_press=self.callback)
            self.add_widget(btn1)
    
        def callback(self, instance):
            print('The button %s state is <%s>' % (instance, instance.state))
    
    
    class ButtonApp(App):
    
        def build(self):
            return Button_Widget()
    
    
    if __name__ == "__main__":
        ButtonApp().run()
    

    button.kv

    #:kivy 1.10.1
    
    <Button_Widget>:
        size: 100, 100
        canvas:
            Rectangle:
                pos: self.pos
                size: self.size
    

    Output

    Img01