Kivy中向自定义Popup类传递数据时程序崩溃问题求助
问题解决:Kivy Popup初始化崩溃及属性访问问题
你的程序崩溃主要有两个核心原因,我来给你逐个梳理并解决:
1. 自定义Popup初始化未传递必要关键字参数
Kivy的所有Widget子类(包括Popup)在初始化时,必须接收**kwargs并传递给父类的__init__方法,否则kv语言加载组件时会因为参数缺失触发错误,导致程序崩溃。
2. 普通实例变量无法在kv文件中直接访问
你在kv文件里尝试访问select.idea_texto,但idea_texto只是一个普通的实例变量,Kivy的kv语言只能识别继承自kivy.properties.Property类型的属性,所以需要把它改成可响应的属性类型。
修改后的Main.py代码
import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty, StringProperty # 新增StringProperty导入 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): # 定义可被kv语言识别的StringProperty idea_texto = StringProperty('') def __init__(self, idea, **kwargs): # 新增**kwargs参数 super().__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()
修改后的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" BoxLayout: Button: text: 'Cerrar' on_press: root.dismiss() Label: # 直接访问根组件的属性,更简洁直观 text: root.idea_texto
额外说明
- 在kv文件中,
root代表当前规则对应的组件实例,用root.idea_texto比通过idselect访问更直接,也避免了不必要的id引用。 - 把
idea_texto定义为StringProperty后,当这个属性的值变化时,对应的Label文本会自动更新,这也是Kivy属性系统的核心特性之一。
内容的提问来源于stack exchange,提问作者JCAguilar
相关产品推荐
相关产品推荐

