Search code examples
pythonkivykivy-language

Display widget when the user wants to in kivy


it is a simple program but i can not find a way to make it work. i just want to add a widget in boxlayout2 when the user presses the button (and has not writed anything in textinput) which is located in boxlayout1 .The widget do not display in screen.What should i do?

main.py

from kivy.app import App 
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout



class BoxLayout1(BoxLayout):
    def Search(self):
        if self.ids.textinput.text!='':
            BoxLayout2()


class BoxLayout2(BoxLayout):
    def Print(self):
        self.add_widget(Button(text='hello'))




class TestApp(App):
    pass


TestApp().run()

and here is my kivy code

test.kv

<BoxLayout1>:
    BoxLayout:
        Label:
            text:'Hello'
        TextInput:
            id: textinput
        Button:
            text: 'write'
            on_press: root.Search()


BoxLayout:
    orientation: 'vertical'
    BoxLayout1:
    BoxLayout2:

I see the presentation layout i want but the button is nowhere to be found.


Solution

  • To make it clear let's follow the stream of the app you've written.

    1. it creates a BoxLayout and puts BoxLayout1 and BoxLayout2 in it, the second one doesn't have any content. When you click on write, the app checks the content of the text box and if valid, calls the constructor of BoxLayout2! Now at this point it creates an instance of this class, but does not keep it's reference so it will be discarded immediately. Now what you want is to call a function of a currently existing instance, not to create another one. Here's the code:

    python:

    from kivy.app import App 
    from kivy.uix.button import Button
    from kivy.uix.boxlayout import BoxLayout
    from kivy.lang import Builder
    
    
    class BoxLayout1(BoxLayout):
        def Search(self):
            if self.ids.textinput.text!='':
                self.parent.ids.bxl2.addButton()
    #            BoxLayout2()
    
    
    class BoxLayout2(BoxLayout):
        def addButton(self):
            button=Button(text='hello')
            self.add_widget(button)
    

    kivy language:

    <BoxLayout1>:
        BoxLayout:
            Label:
                text:'Hello'
            TextInput:
                id: textinput
            Button:
                text: 'write'
                on_press: root.Search()
    
    
    BoxLayout:
        orientation: 'vertical'
        BoxLayout1:
        BoxLayout2:
            id:bxl2