You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy如何从Python代码触发ModalView弹窗及按钮绑定事件

Kivy应用加载完成后自动弹出ModalView实现方案

问题描述

需要实现Kivy应用加载完成时自动弹出ModalView,目前点击界面按钮可正常触发弹窗显示,需要在Python代码层面调用按钮绑定的打开ModalView逻辑。
原始KV文件参考代码如下:

<Controller>

    <BoxLayout>

        ***a lot of code ***

        Button:
            id: my_id
            text: "text"
            color: txt_color
            size_hint_y: .05
            background_color: btn_color_not_pressed if self.state=='normal' else btn_color_pressed

            on_release:
                Factory.About().open()

<About@ModalView>
    id: about
    auto_dismiss: True

    
    *** some more code ****

实现方案

实现逻辑说明

  • 弹窗触发逻辑和按钮绑定的逻辑完全一致,通过Factory调用自定义的About ModalView类执行open()方法
  • 将触发逻辑放在根组件Controller的初始化方法中,即可在页面组件加载完成后自动触发弹窗

main.py代码

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

from kivy.factory import Factory


kivy.require("1.11.1")


class Controller(BoxLayout):
    def __init__(self):
        super(Controller, self).__init__()
        # 直接调用和按钮一致的弹窗触发逻辑
        Factory.About().open()

class mainApp(App):
    def build(self):
        return Controller()


mainApp().run()

main.kv代码

#:import Factory kivy.factory.Factory


<Controller>
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "THIS IS THE MAIN TEKST"
            color: 1,0,0,1
            size_hint_y:.8
        Button:
            text: "About"
            size_hint_y: .2
            on_release: Factory.About().open()

<About@ModalView>

    size_hint: .8,.5

    BoxLayout
        orientation: "vertical"
        size: self.width, self.height
        pos_hint: {"center_x": .5}
        size_hint: .8,.6


        Label:
            text: "ABOUT MY APP"
            color: 0,1,0,1
        Button:
            text: "Back"
            size_hint_y: .2
            on_release: root.dismiss()

运行效果

运行效果截图

内容的提问来源于stack exchange,提问作者thj001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 15:54:03