Justin
Justin

Reputation: 125

trouble with scope related variables

Hello fellow programmers, I'm developing a simple interface application in Python that will enable easy and intuitive entry of inventory forms in an access database.

I currently have a function as follows:

def spawnerror(self, errormsg):
    self.running = False
    content = Button(text=errormsg)
    popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
    content.bind(on_press=popup.dismiss)
    popup.open()

And I have appropriate error handling done, and the application uses this function as intended. For example, if someone doesn't enter in a required field, it calls this function and spawns an error page with an error and informs the user.

My issue that I run into is that, it needs to set the class variable running to False, because at the end of the main function "submit" it checks for that and if self.running == False, then it needs to skip the execution of data entry in the access database.

Why is this function not setting the class variable of running to false?

Upvotes: 0

Views: 36

Answers (1)

ikolim
ikolim

Reputation: 16011

Solution - using App.get_running_app()

In the example, a class attribute, running is defined as BooleanProperty. In the spawnerror() function, it uses App.get_running_app() function to get an instance of App class and then access variable, running.

Note

If running, spawnerror() function and submit() function are in different classes then work out the relation of the classes and pass a direct reference between them.

Example

main.py

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ObjectProperty


class RootWidget(BoxLayout):
    instance = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.instance = App.get_running_app()
        self.spawnerror('Testing')

    def spawnerror(self, errormsg):
        self.instance.running = False
        content = Button(text=errormsg)
        popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
        content.bind(on_press=popup.dismiss)
        popup.open()


class TestApp(App):
    running = BooleanProperty(True)

    def build(self):
        print("\nbuild:")
        self.display_attributes()
        return RootWidget()

    def on_stop(self):
        print("\non_stop:")
        self.display_attributes()

    def display_attributes(self):
        print("\tApp.running =", self.running)


if __name__ == "__main__":
    TestApp().run()

Output

Img01

Upvotes: 1

Related Questions