2016-07-07 54 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

不,在另一個類 –

相關問題