How to add a new button to the screen when you click on the button?

39 views
Skip to first unread message

ТН Н

unread,
Feb 7, 2021, 4:43:03 PM2/7/21
to Kivy users support
Hello! I don't quite understand how to add a new button to the screen when you click on the button, can you please explain? Here is my code, nothing happens, but it does not give an error.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition

Builder.load_string('''
<Start>:
    BoxLayout:
        Button:
            text: '+'
            on_release: root.add_btn()
''')



class Start(Screen):
    def add_btn(self):
        layout = BoxLayout()
        btn = Button(text = 'New button')
        layout.add_widget(btn)
    
sm = ScreenManager(transition = NoTransition())
sm.add_widget(Start(name = 'one'))

class MyApp(App):  
    def build(self):
        return sm

        

MyApp().run()


Elliot Garbus

unread,
Feb 7, 2021, 4:57:42 PM2/7/21
to kivy-...@googlegroups.com

You were creating a layout that is not connected to the widget tree, and adding the button to it…

You can use an id to address the BoxLayout instanced in kv.  In the example below I have used the id box, and added the button to the box BoxLayout.

 

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition

Builder.load_string(
'''
<Start>:
    BoxLayout:
        id: box

        Button:
            text: '+'
            on_release: root.add_btn()
'''
)


class Start(Screen):
   
def add_btn(self):
       
# layout = BoxLayout()
       
btn = Button(text='New button')
       
self.ids.box.add_widget(btn)


sm = ScreenManager(
transition=NoTransition())
sm.add_widget(Start(
name='one'))


--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/d2060c06-a8b8-44eb-abbb-b9a161f52b8fo%40googlegroups.com.

 

ТН Н

unread,
Feb 7, 2021, 5:09:23 PM2/7/21
to Kivy users support
Thanks. Again, very useful.

понедельник, 8 февраля 2021 г., 0:57:42 UTC+3 пользователь ElliotG написал:

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages