Search code examples
tabskivydefault

Kivy: how to define which Tab is to be active on opening a TabbedPanel


how do I define which tab is active when opening a TabbedPanel?

Here I'm using tabs along the left side, and so want tab #3 to be active at the start, not tab #1.

import kivy, os
from  kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.base import runTouchApp


Builder.load_string("""

<TabbedTestScreen>:

    TabbedPanel:
        do_default_tab: False
        tab_pos: 'left_top'
        tab_height: 90
        tab_width: 90

        TabbedPanelItem:
            text: '1'
            Label:
                text: '1'
        TabbedPanelItem:
            text: '2'
            Label:
                text: '2'
        TabbedPanelItem:
            text: '3' 
            id: home_tab
            Label:
                text: '3'                    

""")

class TabbedTestScreen(Screen):
    pass

runTouchApp(TabbedTestScreen())

Solution

  • You can use switch_to to do this at the initialization of your class:

    from  kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import Screen
    from kivy.base import runTouchApp
    from kivy.properties import ObjectProperty
    from kivy.clock import Clock
    
    
    
    Builder.load_string("""
    
    <TabbedTestScreen>:
        tab_panel: tab_panel
        home_tab: home_tab
        TabbedPanel:
            id: tab_panel
            do_default_tab: False
            tab_pos: 'left_top'
            tab_height: 90
            tab_width: 90
    
            TabbedPanelItem:
                text: '1'
                Label:
                    text: '1'
            TabbedPanelItem:
                text: '2'
                Label:
                    text: '2'
            TabbedPanelItem:
                text: '3' 
                id: home_tab
                Label:
                    text: '3'                    
    """)
    
    class TabbedTestScreen(Screen):
        tab_panel = ObjectProperty(None)
        home_tab = ObjectProperty(None)
    
        def __init__(self, **kwargs):
            super(TabbedTestScreen, self).__init__(**kwargs)
            Clock.schedule_once(lambda *args: self.tab_panel.switch_to(self.home_tab))
    
    
    
    runTouchApp(TabbedTestScreen())