How to add a class to the root class?

7 views
Skip to first unread message

Mario

unread,
Nov 25, 2021, 3:25:23 PM11/25/21
to Kivy users support

When clicking a button, I want to add a custom kivy class (<BallImage>) to the root class (MainWidget), but it seems a lot more complicated than it should be..?

  • I can't do self.ids.box.add_widget(self.ids.ball) because ID's are not global.
  • I only have a complicated solution with Clock.schedule_interval which I'd really like to avoid (aren't there something simpler?).
  • As you can see in the code below, self.ids.box.add_widget(BallImage()) doesn't work either.

Help is much appreciated, thanks!


.kv code:

MainWidget:

    BoxLayout:

        id: box


         Button:

             text: "Button"

             on_press: root.add_img()

 

<BallImage@Image>:

    id: ball

    source: "images/ball.png"


.py code:

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout


class BallImage():

    pass


class MainWidget(BoxLayout):

    def add_img(self):

        self.ids.box.add_widget(BallImage())


class ClickApp(App):

    pass


ClickApp().run()

Elliot Garbus

unread,
Nov 25, 2021, 11:21:45 PM11/25/21
to kivy-...@googlegroups.com

You were very close.  You are instancing the BallImage widget in Python, so the inheritance relationship needs to be defined in python.  Notice BallImage is derived from Image.

 

 

Python:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image

class BallImage(Image):
   
pass

class
MainWidget(BoxLayout):
   
def add_img(self):
       
self.ids.box.add_widget(BallImage())

class ClickApp(App):
   
pass

ClickApp().run()

 

kv

 

MainWidget:
   
BoxLayout:
       
id: box

       
Button:
           
text: "Button"
           
on_press: root
.add_img()

<BallImage>:
   
source: "images/ball.png"

--
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/a5fb0249-71ea-482b-8d7d-001240edde05n%40googlegroups.com.

 

Reply all
Reply to author
Forward
0 new messages