Gilgamesch von Uruk
Gilgamesch von Uruk

Reputation: 371

kivy error NameError: global name 'app' is not defined

I wanted to make an App, with two languages(German and English) and settings, so I can switch between the languages. As the languages class is part of the App, I need to acsess it using app.Lanuage, but I got the error message above.

from kivy.app import App
from kivy.lang import Builder

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.settings import SettingsWithSidebar

from setjson import *

Builder.load_string('''
<Interface>:
    orientation: 'vertical'
    Button:
        text: app.Lanuage.first_caption
        font_size: 150
        on_release: app.open_settings()
''')

class Interface(BoxLayout):
    def __init__(self, **kwargs):
        super(Interface, self).__init__(**kwargs)
        self.test = app.Lanuage.all_button

class SettingsApp(App):
    def build(self):
        config = SettingsApp.get_running_app().config
        language = config.getdefault("example", "optionsexample", "English").lower()

        if language == 'english':
            from lang_engl import Lang
        if language == 'deutsch':
            from lang_deutsch import Lang
        self.Lanuage = Lang()

        self.settings_cls = SettingsWithSidebar
        self.use_kivy_settings = False
        setting = self.config.get('example', 'boolexample')
        return Interface()

    def build_config(self, config):
        config.setdefaults('example', {
            'optionsexample': 'English',
            'stringexample': 'some_string',
            'pathexample': '/some/path'})

    def build_settings(self, settings):
        settings.add_json_panel('Panel Name',
                self.config,
                data=settings_json)

    def on_config_change(self, config, section, key, value):
        print 'value: ' + str(value)


SettingsApp().run()

Upvotes: 0

Views: 1910

Answers (1)

Peter Badida
Peter Badida

Reputation: 12179

Example:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<MyBtn>:
    text: str(self)+self.a.test
<Test>:
    Button:
        text: str(self)+app.test
    MyBtn:
''')


class Test(BoxLayout):
    pass


class MyBtn(Button):
    def __init__(self, **kw):
        super(MyBtn, self).__init__(**kw)
        self.a = App.get_running_app()


class My(App):
    test = '\nHi!'

    def build(self):
        return Test()
My().run()
  • use app keyword to get app in kv
  • use App.get_running_app() if you want to use app in python
  • use self.<object> inside App class(inside build(self))

Other than that, I don't see any other issues you could encounter if you actually access the App in your code.

Upvotes: 1

Related Questions