2016-07-07 56 views
0

我想制作一个包含两种语言(德语和英语)和设置的应用程序,以便我可以在各种语言之间切换。 由于语言类是应用程序的一部分,我需要使用app.Lanuage进行操作,但是我收到了上述错误消息。kivy error NameError:未定义全局名称'app'

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() 
+0

你只在范围内有'App',所以无论你的意思是'App.Language'还是你的意思是'kivy.app'模块,那么它将是'kivy.app.Language'或'从kivy导入应用程序; app.Language'。其实我没有在我的kivy包中。你确定kivy有语言课/模块吗? – syntonym

+0

不,我自己创建了语言课程,并将其实例添加到应用程序中。而且,它在kivy语言中工作得非常好,但在python中不适用 –

+1

啊,你想要引用当前的应用程序。你可以通过'App.get_running_app()'[documentation](https://kivy.org/docs/api-kivy.app.html#kivy.app.App.get_running_app)获得。 – syntonym

回答

1

例子:

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() 
  • 使用app关键字,以得到应用中kv
  • 使用App.get_running_app()如果你想使用的应用程序在python
  • 使用self.<object>App类(内build(self)

除此之外,如果您实际访问代码中的App,我不会看到任何其他可能遇到的问题。

+0

为什么App.get_running_app()返回None –

+0

@GilgameschvonUruk你是不是在'App'类中? – KeyWeeUsr

+0

不,在另一个类 –

相关问题