2017-12-12 39 views
0

나는 다음과 같이 kivy (KV)에서 매우 간단한 예제를 수행하려고 :Kivy - Kv 값 - ScreenManager로 - 현재 화면을 변경

#:import Toolbar kivymd.toolbar.Toolbar 

BoxLayout: 
    orientation: 'vertical' 
    Toolbar: 
     id: toolbar 
     title: 'My Toolbar' 
     md_bg_color: app.theme_cls.primary_color 
     background_palette: 'Primary' 
     background_hue: '500' 
     left_action_items: [['arrow-left', app.root.ids.scr_mngr.current = 'screen1' ]] 
     right_action_items: [['arrow-right', app.root.ids.scr_mngr.current = 'screen2' ]] 
    ScreenManager: 
     id: scr_mngr 
     Screen: 
      name: 'screen1' 
      Toolbar: 
       title: "Screen 1" 
     Screen: 
      name: 'screen2' 
      Toolbar: 
       title: "Screen 2" 

left_action_items 및 right_action_items 두 쌍의 목록을 기대하기 때문 실패를 : [name_of_icon, 표현식]. 당신이 버튼을 다룰 때 우리는 같은 것을 할 경우 반면에, 문이 예를 들어 법률 것 :

on_release: 
    app.root.ids.scr_mngr.current = 'screen1' 

한편을 left_action_item에 대한 올바른 접근 방식이 될 것 같은 뭔가 :

left_action_items: [['arrow-left', lambda x: app.root.ids.scr_mngr.current = 'screen1' ]] 

그러나 이것은 합법적이지 않습니다. 왜냐하면 파이썬에서 람다 (lambda)에서 그러한 assigment를 수행 할 수 없기 때문입니다.

화면을 변경하려면 left_action_items에 대한 올바른 접근 방식은 무엇입니까?

답변

0

루트 클래스를 파이썬 클래스로 만들 수 있으며 거기에 change_screen 메소드가있을 수 있습니다. 또한 스크린 관리자를 루트 클래스의 ObjectProperty로 만듭니다.
그런 다음 kv에서 partial을 사용하여 메서드에 인수를 전달할 수 있습니다.
다음과 같이하십시오 :

여러 옵션이 있습니다
from kivy.app import App 
from kivy.lang import Builder 
from kivy.properties import ObjectProperty 
from kivy.uix.boxlayout import BoxLayout 
from kivymd.theming import ThemeManager 

class MyLayout(BoxLayout): 

    scr_mngr = ObjectProperty(None) 

    def change_screen(self, screen, *args): 
     self.scr_mngr.current = screen 


KV = """ 
#:import Toolbar kivymd.toolbar.Toolbar 
#:import partial functools.partial 

MyLayout: 
    scr_mngr: scr_mngr 
    orientation: 'vertical' 
    Toolbar: 
     id: toolbar 
     title: 'My Toolbar' 
     left_action_items: [['arrow-left', partial(root.change_screen, 'screen1') ]] 
     right_action_items: [['arrow-right', partial(root.change_screen, 'screen2') ]] 
    ScreenManager: 
     id: scr_mngr 
     Screen: 
      name: 'screen1' 
      Toolbar: 
       title: "Screen 1" 
     Screen: 
      name: 'screen2' 
      Toolbar: 
       title: "Screen 2" 
""" 


class MyApp(App): 
    theme_cls = ThemeManager() 

    def build(self): 
     return Builder.load_string(KV) 


MyApp().run() 
+0

작동합니다. ScreenManager가 다음과 같은 일을 할 수있는 가능성을 부여하지 않는다는 점이 불행입니다. set_screen ('screen1') – mantielero

+0

@mantielero가 질문에 대답하지 않습니까? – EL3PHANTEN

0

, 나중에

left_action_items: [('arrow-left', (app.root.ids.scr_mngr, 'current', 'screen1'))] 

을 할 수 있습니다 수행

for icon, expr in self.left_action_items: 
    setattr(*expr) 

당신이 정말 당신이 할 수있는 실행 표현을 원하는 경우 :

left_action_items: [('arrow-left', lambda: setattr(app.root.ids.scr_mngr, 'current' 'screen1'))]