Kivy如何通过on_touch_down点击MDCard跳转第二屏并传递点击数值
实现方案
核心问题说明
你现有代码存在两个核心问题:
- 循环中使用
self.x存储数值,循环结束后self.x会固定为最后一次的取值9,所以点击任意卡片都会拿到同一个值 - 没有实现屏幕切换逻辑和跨屏传值的逻辑
具体修改步骤
1. 修改Python代码部分
给第二屏新增接收数值的属性
给SecondWindow类新增StringProperty属性用来接收第一屏传递的数字:
class SecondWindow(Screen): selected_num = StringProperty("")
修改卡片创建逻辑
循环中不要用self.x,给每个卡片单独绑定自身对应的数值:
# 把原代码中for self.x in range(10)替换为以下逻辑 for x in range(10): card = MDCard(orientation='vertical', size_hint=(1, None), height=200 ,padding=(20,0),ripple_behavior= True,radius=[5, ]) card.add_widget(MDLabel(text=str(x), halign= "center")) # 给卡片新增自定义属性存储对应数值 card.number = x layout.add_widget(card) card.bind(on_touch_down=self.clicked)
修改点击事件函数
实现传值和屏幕跳转逻辑:
def clicked(self, card, touch): if card.collide_point(*touch.pos): # 获取屏幕管理器 sm = self.manager # 给第二屏赋值 sm.get_screen('SecondWindow').selected_num = str(card.number) # 切换到第二屏 sm.current = 'SecondWindow' # 返回True表示消费当前触摸事件,避免事件继续向下传递 return True return super().on_touch_down(touch)
2. 修改KV代码部分
修改第二屏的Label,让它显示传递过来的数值:
<SecondWindow>: name:"SecondWindow" BoxLayout: orientation: 'vertical' canvas.before: Color: rgba: .2, .2, .2, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' # 绑定第二屏的selected_num属性展示数值 Label: text: f"你点击的卡片数字是:{root.selected_num}" Button: text:"返回第一页" on_release: app.root.current = "FirstWindow"
内容的提问来源于stack exchange,提问作者primitiveProgrammer
相关产品推荐
相关产品推荐

