Kivy:将数据传递给另一个类弹出窗口

时间:2018-01-21 13:02:52

标签: python python-3.x popup kivy

我正在尝试用Kivy(1.10)python 3.4.4创建一个简单的GUI,使用弹出窗口显示另一个类的信息。但是当我使用函数 init 将变量从一个类(主体)传递给使用popup(Seleccionador)构造的类时,我遇到了问题

我使用功能时崩溃(abre_seleccionador)

Main.py

import kivy
kivy.require('1.10.0')

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from kivy.config import Config

Config.set('graphics','width', 800)
Config.set('graphics','height',500)

class CustomPopup(Popup):
    pass

class Seleccionador(Popup):

    def __init__(self,idea):
        super().__init__()
        self.idea_texto =idea

class Principal(BoxLayout):
    def abre_popup(self):

        the_popup =CustomPopup()
        the_popup.open()

    def abre_seleccionador(self):
        idea ='idea brillante'
        popin= Seleccionador(idea)
        popin.open()

class KvpopApp(App):
    title = 'Pruebas de pop up y filechooser'
    def build(self):
        return Principal()

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

kv文件:

<Principal>:
    orientation:'vertical'
    canvas:
        Color:
            rgb: 1,1,1,
        Rectangle:
            pos: self.pos
            size: self.size
    Button:
        text: 'Abrir popup'
        on_press: root.abre_popup()
    Button:
        text: 'Abre seleccionador'
        on_press: root.abre_seleccionador()

<CustomPopup>:
    size_hint: 0.5,0.5
    auto_dismiss: False
    title: "Este es mi Popup"
    Button:
        text: 'Cerrar popup'
        on_press: root.dismiss()

<Seleccionador>:
    size_hint: 0.5,0.5
    auto_dismiss: False
    title: "Este es mi Popup"
    id: select
    BoxLayout:
        Button:
            text: 'Cerrar'
            on_press: root.dismiss()
        Label:
            id: idea
            text: select.idea_texto

1 个答案:

答案 0 :(得分:0)

在初始化类之前(在执行__init__方法之前)评估Kv语言规则,因此当时不存在实例属性。最简单的是你使用StringProperty

from kivy.app import App
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty


Config.set('graphics', 'width', 800)
Config.set('graphics', 'height',500)


class CustomPopup(Popup):
    pass


class Seleccionador(Popup):
    idea_texto = StringProperty()    # <<<<<<<<<<<<<<<<<<<<

    def __init__(self, idea, **kwargs):
        super(Seleccionador, self).__init__(**kwargs)
        self.idea_texto = idea

class Principal(BoxLayout):
    def abre_popup(self):
        the_popup = CustomPopup()
        the_popup.open()

    def abre_seleccionador(self):
        idea = 'idea brillante'
        popin = Seleccionador(idea)
        popin.open()


class KvpopApp(App):
    title = 'Pruebas de pop up y filechooser'

    def build(self):
        return Principal()


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