Search code examples
python-3.xkivykivy-language

python kivy : How to make switch Button work with carousel


I get:

AttributeError: 'Carousel' object has no attribute 'switch_on'

error whenever I try to click on the button

-------main.py----------

class main(App):
    def build(self):



        class SampBoxLayout(BoxLayout):


            # For Switch
            def switch_on(self, instance, value):
                if value is True:
                    print("Switch On")
                else:
                    print("Switch Off")



        return Carousel()



sample_app = kv_main()
sample_app.run()

----------main.kv--------------

:

Label:
    text: "Page 1"
    size_hint: 1, .1
    width :100

    SampBoxLayout:


        # ----------Switch ----------
        BoxLayout:

            BoxLayout:
                orientation: "horizontal"
                size_hint_x: .25
                CustLabel:
                    text: "On / Off"

                    Switch:
                        id: switch_id
                        on_active: root.switch_on(self, self.active)# <--need help on this


Label:
    text: "Page 2"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 2.1"
        size_hint: None, None
        width :100



Label:
    text: "Page 3"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 3.1"
        size_hint: None, None
        width :100

Solution

  • You are using root.switch_on. As the error indicates, your root class is the carousel. Since SampBoxLayout is not root, you should give SampBoxLayout an id, and call it with it´s id.
    Edited from your example:

    SampBoxLayout:
        id: samp
        BoxLayout:
    
            BoxLayout:
                orientation: "horizontal"
                size_hint_x: .25
                CustLabel:
                    text: "On / Off"
    
                    Switch:
                        id: switch_id
                        on_active: samp.switch_on(self, self.active)
    

    I don't know if you did something wrong when posting this, or if your code really looks like this. But you should not define classes inside your app class. Keep the classes on top level to access them in kv.
    And your kv code is unusual. You have your widgets in a label.