Kivy ScreenManager点击按钮后循环切换屏幕而非跳转至目标屏幕
问题原因与解决方案
问题根源
MDNavigationRailItem的on_active事件会在**选中(active=True)和取消选中(active=False)**两种状态变化时都触发。当你点击一个新的导航项时:
- 原选中项的
active变为False,触发它的on_active回调,将ScreenManager切回对应屏幕; - 新点击项的
active变为True,触发它的on_active回调,将ScreenManager切到目标屏幕; - 这种交替触发就导致了屏幕循环切换的现象。
修复方案
有两种可靠的修复方式:
方式一:仅在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
相关产品推荐
相关产品推荐

