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

如何在Kivy中跨类传递Spinner组件的选中值作为变量

解决Kivy Spinner选中方向在主App类中打印的问题

原代码存在的问题

  • MenuKV中的spun和value是类属性,而on_spinner_select方法修改的是实例属性,两者互不关联,导致主App类无法获取到选中的方向值。
  • MenuScreen的build方法仅在应用启动时执行一次,Spinner选择方向后不会触发该方法中的打印逻辑。

修正后的代码

main.py

from kivy.uix.widget import Widget
from kivy.app import App
from kivy.properties import StringProperty, BooleanProperty


class MenuKV(Widget):
    # 使用Kivy专属属性实现属性变化监听,适配框架机制
    spun = BooleanProperty(False)
    selected_direction = StringProperty('North')
    
    def on_spinner_select(self, value):
        self.selected_direction = value  
        self.spun = True
        # 获取当前运行的App实例,调用打印方法
        App.get_running_app().print_selected_direction(value)


class MenuScreen(App):
    def build(self):
        return MenuKV()
    
    def print_selected_direction(self, direction):
        print(f"你选择的方向是: {direction}")


if __name__ == "__main__":
    MenuScreen().run()

menuscreen.kv

MenuKV:     

<MenuKV>:
    BoxLayout:
        orientation: 'horizontal'
        pos_hint: {"x":0, "top":1} 
        size_hint: 1, None
        height: "44dp"
        spacing: "10dp"
        padding: "10dp"
        pos: 0, root.height - 60

        Spinner:
            id: direction
            text: root.selected_direction
            values: 'North', 'South', 'East', 'West'
            on_text: root.on_spinner_select(self.text)

        Button:    
            text: "future dev"

修正说明

  1. 属性类型调整:将MenuKV的属性改为Kivy的BooleanProperty和StringProperty,这类属性支持自动通知变化,更符合Kivy的开发规范。
  2. 实例调用逻辑:在on_spinner_select中通过App.get_running_app()获取当前App实例,直接调用其打印方法,确保选中方向后立即触发打印。
  3. KV文件绑定优化:Spinner的text绑定到root.selected_direction,实现UI与数据的双向同步。
  4. App类逻辑调整:build方法返回MenuKV的实例,确保后续能正确访问实例的属性和方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:22:56