Search code examples
pythonkivykivy-language

Kivy closeable TabbedPanel


I tried extracting the code for a closeable TabbedPanel from github here.

It works all fine but the content of the tab is not cleared as well, just the header. How can I remove the content of the Tab when closing it as well?

from kivy.app import App
from kivy.animation import Animation
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelHeader
from kivy.factory import Factory
from kivy.lang import Builder


class CloseableHeader(TabbedPanelHeader):
    pass

class TestTabApp(App):
    def build(self):
        return Builder.load_string('''
TabbedPanel:
    do_default_tab: False
    FloatLayout:
        BoxLayout:
            id: tab_1_content
            Label:
                text: 'Palim 1'
        BoxLayout:
            id: tab_2_content
            Label:
                text: 'Palim 2'
        BoxLayout:
            id: tab_3_content
            Label:
                text: 'Palim 3'


    CloseableHeader:
        text: 'tab1'
        panel: root
        content: tab_1_content.__self__
    CloseableHeader:
        text: 'tab2'
        panel: root
        content: tab_2_content.__self__
    CloseableHeader:
        text: 'tab3'
        panel: root
        content: tab_3_content.__self__


<CloseableHeader>
    color: 0,0,0,0
    disabled_color: self.color
    # variable tab_width
    text: 'tabx'
    size_hint_x: None
    width: self.texture_size[0] + 40
    BoxLayout:
        pos: root.pos
        size_hint: None, None
        size: root.size
        padding: 3
        Label:
            id: lbl
            text: root.text
        BoxLayout:
            size_hint: None, 1
            orientation: 'vertical'
            width: 22
            Button:
                on_press:
                    root.panel.remove_widget(root)

''')


if __name__ == '__main__':
    TestTabApp().run()

If I close tab 2, while being on tab 2. enter image description here

I would like to see tab 1, right now I will still see the content of tab2.

enter image description here


Solution

  • As you said, in your code you just remove header. To also clear all the widgets in the content area, you have to add the following command:

    Button:
        on_press:
            root.panel.switch_to(root.panel.tab_list[root.panel.tab_list.index(root.panel.current_tab) - 1])
            root.panel.remove_widget(root)
            root.content.clear_widgets()
    

    Now the content area is cleared and another content is shown.