首页 > 解决方案 > Kivy - 如何从 Python 代码触发模型视图

问题描述

我想在加载应用程序时强制启动 ModalView,但我不知道该怎么做。

当我按下按钮时它工作正常,但我不知道如何从 python 文件触发事件。

我如何从代码中触发事件(按钮)?

.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 ****

如何从我的 main.py 调用事件?

** 来自@john Anderson 的解决方案之后 **

文件: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()

在此处输入图像描述

标签: pythonkivymodal-view

解决方案


About ModalView是在__init__()您的根Controller小部件的方法中创建的。这意味着它是在您的Controller. About一个简单的解决方法是将小部件的创建延迟到App启动之后。您可以使用该App方法on_start()来做到这一点:

class Controller(BoxLayout):
    pass


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

    def on_start(self):
        Factory.About().open()

推荐阅读