KivyMD跨类调用:点击ContentButton按钮触发TelaFechamento类方法
问题原因
你当前代码报错的核心是对KV语法里的上下文关键字指代理解有误:
- 在
<ContentButton>的KV规则块中,root指代的是ContentButton类本身的实例,这个类没有定义fechar_pedido方法,所以直接写root.fechar_pedido()会触发属性不存在的报错 - 你之前尝试的
root.get_screen(...)写法问题同理,ContentButton不是ScreenManager实例,本身没有get_screen方法,自然调用失败
KV里三个常用上下文关键字的固定指代:
root:当前KV规则对应的最外层组件实例app:全局唯一的当前运行中的App实例,任意KV规则块中都可以直接访问self:当前编写KV规则的组件本身,比如按钮规则里self就是这个按钮对象
实现方案
给你两种可直接运行的实现方式,按需选择即可。
方案1:全局快速调用(适合小型项目)
直接通过全局app实例拿到根组件(多屏项目一般默认根组件为ScreenManager),再获取目标屏幕实例调用方法,不需要修改Python端的类逻辑,只需要修改KV中按钮的回调配置:
<ContentButton> orientation: 'vertical' adaptive_height: True MDFillRoundFlatButton: size_hint: .9, None pos_hint: {'center_x': .5, 'center_y': .5} text: "Fechar Pedido" on_release: app.root.get_screen('tela_fechamento').fechar_pedido()
方案2:回调传参(低耦合,推荐中大型项目用)
给ContentButton增加回调参数,实例化的时候把目标方法传进去,不需要硬编码屏幕名称,后续组件复用更灵活:
- 修改Python端的
ContentButton类,增加回调接收逻辑:class ContentButton(MDBoxLayout): '''Custom content.''' def __init__(self, close_callback=None, **kwargs): super().__init__(**kwargs) self.close_callback = close_callback - 修改KV中按钮的回调逻辑:
<ContentButton> orientation: 'vertical' adaptive_height: True MDFillRoundFlatButton: size_hint: .9, None pos_hint: {'center_x': .5, 'center_y': .5} text: "Fechar Pedido" on_release: root.close_callback() if root.close_callback else None - 修改
TelaFechamento.pedidos_abertos方法中实例化ContentButton的代码,把目标方法传进去:# 把原来的 cw.add_widget(ContentButton()) 替换成下面这行 cw.add_widget(ContentButton(close_callback=self.fechar_pedido))
内容的提问来源于stack exchange,提问作者Elias Coutinho
相关产品推荐
相关产品推荐

