culturoeil
culturoeil

Reputation: 117

Python Kivy Overwritting method

I have tried to minimize the example as much as possible but it seems empty and the problem is not exactly the same after.

I think i misunderstand things about class variables and instance variables, but Kivy doesn't help me on this : we create a lot of class but never instantiate them !

Of course I want the "Screenx instance has overwritten question" message appears and I just see "Not overwritten".

calendrier.py

from kivy.properties import StringProperty
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock

class Menu(Screen):
    pass

class CalculGenerique(Screen):
    question = StringProperty()

    def __init__(self, **kwargs):
        super(CalculGenerique, self).__init__(**kwargs)
        Clock.schedule_once(self.late_init, 0)

    def late_init(self, *largs):
        self.renew_question()

    def renew_question(self):
        self.question = "Not overwritten"

class Screen1(CalculGenerique):
    def renew_question(self):
        self.question = "Screen1 instance has overwritten question"

class Screen2(CalculGenerique):
    def renew_question(self):
        self.question = "Screen2 instance has overwritten question"

class MyScreenManager(ScreenManager):
    pass

class CalendarApp(App):

    def build(self):
        root_widget = Builder.load_file("calendrier.kv")
        return root_widget

if __name__ == "__main__":
    app = CalendarApp()
    app.run()

calendrier.kv

#:import App kivy.app.App

MyScreenManager:
    Menu:
    CalculGenerique:
        name: 'Screen1'
    CalculGenerique:
        name: 'Screen2'

<Menu>:
    name: 'Menu'
    BoxLayout:
        orientation: 'vertical'

        Button:
            text: 'Screen1'
            on_press : app.root.current = 'Screen1'

        Button:
            text: 'Screen2'
            on_press : app.root.current = 'Screen2'

        Button:
            text: 'Quitter l app'
            on_press : App.get_running_app().stop()

<CalculGenerique@Screen>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: 'Back to Menu'
            on_press : app.root.current = 'Menu'
        Label:
            text: root.question

Upvotes: 0

Views: 150

Answers (1)

John Anderson
John Anderson

Reputation: 38882

Your 'kv' rule:

MyScreenManager:
    Menu:
    CalculGenerique:
        name: 'Screen1'
    CalculGenerique:
        name: 'Screen2'

creates two instances of the CalculGenerique class, but no instances of Screen1 or Screen2. I think you just need to change that rule to:

MyScreenManager:
    Menu:
    Screen1:
        name: 'Screen1'
    Screen2:
        name: 'Screen2'

The name property of a Screen is just used to identify the Screen, and does not specify the class.

Upvotes: 1

Related Questions