Python KIVY:按下按钮显示/隐藏布局

时间:2018-02-17 14:48:58

标签: python kivy

我正在创建一个小界面,左边是垂直菜单,右边是空闲区域。 由于左侧的绿色按钮,我希望用户隐藏或显示菜单。 当我点击这个按钮时,我希望菜单在可见时消失,或者如果它不可见则显示

的.py:

import kivy
kivy.require('1.10.0')

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

class SM(ScreenManager):

    def __init__(self, **kwargs):
        super(SM, self).__init__(**kwargs)

class Main(Screen):

    def __init__(self, **kwargs):
        super(Main, self).__init__(**kwargs)

    def show_hide(self, menu):
        # ...
        pass

Builder.load_file("gui.kv")

class GUI(App):

    def build(self):
        return SM()

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

.kv:

#:kivy 1.10.0

<SM>:
    Main:
        name: "main_screen"
        id: main_screen

<Main>:

    GridLayout:
        cols: 3

        Button: # <--- Show / Hide button
            size: (8,8)
            size_hint: (None, 1)
            text: "|"
            background_color: (0,1,0,1)
            on_press: root.show_hide(menu)

        BoxLayout: # <--- I want to show/hide this menu
            id: menu
            orientation: 'vertical'
            size: (120, 120)
            size_hint: (None, 1)

            Button:
                text: "Menu button"
            Button:
                text: "Menu button"
            Button:
                text: "Menu button"
            Button:
                text: "Menu button"

        BoxLayout:
            Button:
                text:"( ** nothing ** )"

1 个答案:

答案 0 :(得分:0)

对于这种情况我们可以使用BoxLayout的宽度和不透明度,我们还创建了一个布尔属性:

<强> *。PY

class Main(Screen):
    isShownMenu = BooleanProperty(True)
    def __init__(self, **kwargs):
        super(Main, self).__init__(**kwargs)

<强> .kv

<Main>:
    GridLayout:
        cols: 3
        Button: # <--- Show / Hide button
            size: (8,8)
            size_hint: (None, 1)
            text: "|"
            background_color: (0,1,0,1)
            on_press: root.isShownMenu = not root.isShownMenu

        BoxLayout: # <--- I want to show/hide this menu
            id: menu
            orientation: 'vertical'
            width: 120 if root.isShownMenu else 0
            hight: 120
            size_hint: (None, 1)
            opacity: 1 if root.isShownMenu else 0

            Button:
                text: "Menu button"
            Button:
                text: "Menu button"
            Button:
                text: "Menu button"
            Button:
                text: "Menu button"