Search code examples
pythonkivykivy-languagekivymd

Kivy How to Access Widgets inside Child Widgets


In this code, there is a Button and I have made a Toggle Button inside the Main button. ON pressing the main button, I want the state of the Toggle Button to be "down". How can I do so?

Main Code:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import Screen,ScreenManager

class Main(Screen):
    def onbtn(self,widget):
        for child in self.ids.Fl.children:
            if isinstance(child, ToggleButton): # This part is wrong... How to access Widgets inside child Widgets?
                child.state='down'

class Manager(ScreenManager):
    pass
kv=Builder.load_file("test2.kv")
screen=Manager()
screen.add_widget(Main(name="main"))

class Test(App):
    def build(self):
        return screen

Test().run()

Kv Code:

<Main>:
    name: "main"
    FloatLayout:
        id: Fl
        Button:
            id: btn1
            text: "BTN 1"
            size_hint: (.5,.3)
            pos_hint: {"center_x":.5,"center_y":.6}
            on_press:
                root.onbtn(self)
            ToggleButton:
                id: tglbtn1 # How to Access this button to change its state to down
                size: 80,80
                text: "TGL BTN 1"
                pos: 500,400

Solution

  • Just change:

    class Main(Screen):
        def onbtn(self,widget):
            for child in self.ids.Fl.children:
                if isinstance(child, ToggleButton): # This part is wrong... How to access Widgets inside child Widgets?
                    child.state='down'
    

    to:

    class Main(Screen):
        def onbtn(self,widget):
            for child in widget.children:
                if isinstance(child, ToggleButton):
                    child.state='down'
    

    The widget that is passed into the onbtn() method is the Button.