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

如何在Python Kivy中点击首屏按钮修改次屏Label文本

Kivy多屏幕应用跨屏幕修改Label文本解决方案

问题需求

需要实现以下功能:

  • 点击第一个屏幕(Screen1)的两个按钮,分别将第二个屏幕(Screen2)上Label的文本修改为“1st text”和“2nd text”
  • 两个屏幕可通过按钮互相切换

修改后的完整代码

Python代码

import kivy
kivy.require("1.10.1")
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.app import App

class Screen1(Screen):
    pass

class Screen2(Screen):
    pass

class Select_text(App):
    def build(self):
        sm = ScreenManager(transition=FadeTransition())
        sm.add_widget(Screen1(name = "scr1"))
        sm.add_widget(Screen2(name = "scr2"))
        
        return sm

if __name__ == "__main__":
    app = Select_text()
    app.run()

KV代码

<Screen1>:
    orientation: "vertical"
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: "Background.png"
            
    Button:
        id: change_to_1
        pos: (root.width-self.width)/2, 400
        size: 1200, 200
        size_hint: None, None
        text: "Change the text on the 2nd screen to »1st text«"
        on_press: root.manager.get_screen('scr2').ids.text.text = "1st text"
        
    Button:
        id: change_to_2
        pos: (root.width-self.width)/2, 800
        size: 1200, 200
        size_hint: None, None
        text: "Change the text on the 2nd screen to »2nd text«"
        on_press: root.manager.get_screen('scr2').ids.text.text = "2nd text"
        
    Button:
        id: go_to_other_screen
        pos: (root.width-self.width)/2, 1400
        size: 600, 200
        size_hint: None, None
        text: "Go to other screen"
        on_press: root.manager.current = "scr2"
        
<Screen2>:
    orientation: "vertical"
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: "Background.png"
            
    Label:
        id: text
        text: "Text which should be changed"
        pos: (root.width-self.width)/2, 800
        size: 600, 200
        
    Button:
        id: go_to_other_screen
        pos: (root.width-self.width)/2, 1400
        size: 600, 200
        size_hint: None, None
        text: "Go to other screen"
        on_press: root.manager.current = "scr1"

核心逻辑说明

  • root.manager:获取当前屏幕所属的ScreenManager实例
  • get_screen('scr2'):通过屏幕名称获取Screen2的实例对象
  • ids.text.text:访问Screen2中id为text的Label组件,直接修改其文本属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:02:02