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

Kivy ScreenManager点击按钮后循环切换屏幕而非跳转至目标屏幕

问题原因与解决方案

问题根源

MDNavigationRailItem的on_active事件会在**选中(active=True)和取消选中(active=False)**两种状态变化时都触发。当你点击一个新的导航项时:

  1. 原选中项的active变为False,触发它的on_active回调,将ScreenManager切回对应屏幕;
  2. 新点击项的active变为True,触发它的on_active回调,将ScreenManager切到目标屏幕;
  3. 这种交替触发就导致了屏幕循环切换的现象。

修复方案

有两种可靠的修复方式:

方式一:仅在active为True时执行切换

修改每个MDNavigationRailItem的on_active回调,增加self.active判断,只在选中时切换屏幕:

MDNavigationRailItem:
    icon: "account-details-outline"
    on_active: if self.active: sm_cfg.current = "screen_my_account"
MDNavigationRailItem:
    icon: "account-card-outline"
    on_active: if self.active: sm_cfg.current = "screen_user_account"
MDNavigationRailItem:
    icon: "database_cog"
    on_active: if self.active: sm_cfg.current = "screen_db"

方式二:使用MDNavigationRail的选中项变化事件

移除每个item的on_active,改用MDNavigationRail的on_current_selected_item事件统一处理,这种方式更符合组件设计逻辑:

MDNavigationRail:
    id: navigation_rail
    type: "unselected"
    current_selected_item: 0
    on_current_selected_item:
        if args[1] == 0:
            sm_cfg.current = "screen_my_account"
        elif args[1] == 1:
            sm_cfg.current = "screen_user_account"
        elif args[1] == 2:
            sm_cfg.current = "screen_db"
    MDNavigationRailItem:
        icon: "account-details-outline"
    MDNavigationRailItem:
        icon: "account-card-outline"
    MDNavigationRailItem:
        icon: "database_cog"

验证效果

修改后点击导航项,只会触发一次屏幕切换,不会出现循环现象,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:36:27