Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kivy Adding Widget to a screen

Tags:

python

kivy

This seems to be a silly question. But I have a widget that I want to add to a screen called GameScreen.

This is my Python code:

class WelcomeScreen(Screen):
    pass

class BasicScreen(Screen):
    pass

class GameScreen(Screen):
    parent = Widget()
    game =  ShootingGame()
    parent.add_widget(game)
    Clock.schedule_interval(game.update, 1.0 / 60.0)
    # return parent

sm = ScreenManager()
sm.add_widget(WelcomeScreen(name='welcome'))
sm.add_widget(BasicScreen(name='basic'))
sm.add_widget(GameScreen(name='game'))

class ShootingApp(App):
    def build(self):
        print(sm.current)
       return sm

if __name__ == '__main__':  
    ShootingApp().run()

And this is my kivy code:

<WelcomeScreen>:
Button:
    text: "Learn about haptic illusions"
    size_hint: None, None
    size: 500, 70
    pos: 100, 200
    font_size: 30
    on_release: app.root.current = "basic"

Button:
    text: "Play our game"
    size_hint: None, None
    size: 500, 70
    pos: 100, 100
    font_size: 30
    on_release: app.root.current = "game"

<BasicScreen>:
name: "basic"

<GameScreen>:
name: "game"

The error I am getting is this. And I think this is because I already defined a parent for the widget game. However, I need that parent because the game widget uses width and height values of its parent (e.g., self.parent.width). Is there any workaround for this so that the game widget can be nested in a parent and add the parent to the screen?

kivy.uix.widget.WidgetException: Cannot add <Screen name='game'>, it already has a parent <kivy.uix.widget.Widget object at 0x1093dc8d8>

Thanks guys!!

like image 302
susanz Avatar asked Oct 13 '25 09:10

susanz


1 Answers

you can do something like this

class GamesScreen(Screen):
    def __init__(self, **kwargs):
        super(GameScreen, self).__init__(**kwargs)
        self.game = ShootingGame()
        self.add_widget(self.game)
        clock.schedule_interval(self.game.update, 1.0 / 60.0)
like image 124
hchandad Avatar answered Oct 14 '25 22:10

hchandad