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

Python Kivy GUI开发:如何在不同Screen类之间传递数据

问题根源
  1. 你在TrainNew1.test()方法中赋值的PROJECT_PATH是函数局部变量,并没有修改你最外层定义的全局PROJECT_PATH,方法运行结束后这个局部变量就会被回收,其他类自然读不到。
  2. 你把print(PROJECT_PATH)直接写在TrainNew2类的定义层面,这段代码会在类加载的时候就执行,此时你还没有触发TrainNew1.test()方法赋值,就算全局变量修改成功,这时候读取也是初始空值。
推荐解决方法

Kivy官方更推荐通过App实例或者ScreenManager实例存储跨页面共享变量,比全局变量更易维护,不会出现变量污染问题。

方案1:通过App实例共享(最常用)

把需要跨页面传递的变量定义为App类的属性,任意页面都可以通过App.get_running_app()获取当前App实例读写属性:

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager

class TrainNew1(Screen):
    def test(self):
        # 获取当前运行的App实例,赋值共享属性
        app = App.get_running_app()
        app.project_path = self.ids.ProjectName.text 
        print(f"已存储路径:{app.project_path}")

class TrainNew2(Screen):
    # 进入页面时触发on_enter方法,此时再读取共享值
    def on_enter(self, *args):
        app = App.get_running_app()
        print(f"读取到的路径:{app.project_path}")

class MyApp(App):
    # 提前初始化共享属性,规范写法
    project_path = ""
    def build(self):
        sm = ScreenManager()
        sm.add_widget(TrainNew1(name="train1"))
        sm.add_widget(TrainNew2(name="train2"))
        return sm

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

方案2:通过ScreenManager实例共享

如果变量仅需要在Screen之间传递,也可以直接存到ScreenManager的属性中:

class TrainNew1(Screen):
    def test(self):
        # self.manager就是当前页面所属的ScreenManager实例
        self.manager.project_path = self.ids.ProjectName.text
        # 赋值完成后切换到TrainNew2
        self.manager.current = "train2"

class TrainNew2(Screen):
    def on_enter(self, *args):
        print(f"读取到的路径:{self.manager.project_path}")

补充:强制使用全局变量的修改方式(不推荐)

如果一定要用全局变量,需要在修改全局变量的方法里加global声明,并且在实际需要使用的时候再读取:

PROJECT_PATH = ""

class TrainNew1(Screen):
    def test(self):
        # 声明要修改的是全局变量,而非局部变量
        global PROJECT_PATH
        PROJECT_PATH = self.ids.ProjectName.text 

class TrainNew2(Screen):
    def get_path(self):
        global PROJECT_PATH
        print(PROJECT_PATH)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:36:03