Kivy - 在父 Widget 中使用 "on_release" 事件

Kivy - Using the "on_release" event in parent Widget

我目前正在尝试触发嵌套在动态 class 中的自定义按钮的 "on_release" 事件。更加具体。这是我当前实现的示例 kv 文件:

#:kivy 1.10.1
#:include gui/components.kv

<MiddleSectionMain@AnchorLayout>:
    anchor_x: 'center'
    anchor_y: 'center'

    lb_text: ''
    text: spinner_1.text
    stateb1: button_1.state 

    BoxLayout:
        orientation: 'horizontal'
        Label:
            text: root.lb_text
            size_hint_x: 0.3
        Spinner:
            id: spinner_1
            text: 'Select'
        IconButtonSmall:
            id: button_1
            icon_source: 'icons/add_32.png'
        IconButtonSmall:
            id: button_2
            icon_source: 'icons/edit_32.png'


<MainScreen>:
    orientation: 'vertical'

    Label:
        font_size: 25
        text: "Headline"

    GridLayout:
        cols: 1

        MiddleSectionMain:
            lb_text: "Label"
            on_stateb1: 
                if self.stateb1 == 'normal': app.root.current = 'Screen2'

        MiddleSectionMain:
            lb_text: "Label"

IconButtonSmall 在另一个 .kv 文件 (gui/components.kv) 中定义。

此实现有效,但我不是很满意,因为按钮还提供了 "on_release" 事件。所以我想知道是否有办法使用 "on_release" 事件而不是我使用 "on_state" 的版本并检查当前状态。

最好的, 朱兹

假设-使用on_releaseon_press事件切换屏幕

以下示例说明如何使用 Button 的事件,on_release 在动态 class 中切换屏幕。

注: 如果您想使用 on_press 事件,请将 on_release 替换为 on_press

  1. 为每个按钮声明 StringProperty,例如btn1_screen_name: ''
  2. 为每个按钮实施 on_release: 事件
  3. 初始化btn1_screen_name: 'Screen2'

片段

<MiddleSectionMain@AnchorLayout>:
    btn1_screen_name: ''
    btn2_screen_name: ''
    ...
    BoxLayout:
        IconButtonSmall:
            id: button_1
            icon_source: 'icons/add_32.png'
            on_release: app.root.current = root.btn1_screen_name
        IconButtonSmall:
            id: button_2
            icon_source: 'icons/edit_32.png'
            on_release: app.root.current = root.btn2_screen_name


<MainScreen>:
    BoxLayout:
        ...
        GridLayout:
            cols: 1

            MiddleSectionMain:
                lb_text: "Label"
                btn1_screen_name: 'Screen2'
                btn2_screen_name: 'MainScreen'

            MiddleSectionMain:
                lb_text: "Label"
                btn1_screen_name: 'Screen3'
                btn2_screen_name: 'MainScreen'