首页 > 解决方案 > 我如何从一个班级获取信息到另一个班级

问题描述

python新手 - kivy - gui

我试图从一个类获取信息到另一个类,这些类基本上是我的 GUI 的不同屏幕。我研究了返回函数,但它根本没有帮助,因为我是个菜鸟。

在 .kv 文件上运行的主 GUI 这是我的代码的细分。

PROJECT_PATH = ""

class TrainNew1(Screen):
    #takes user input,i click a button to submit, runs this function.
    def test(self):
        PROJECT_PATH = self.ids.ProjectName.text 
        #will print PROJECT_PATH fine within test /class function
class TrainNew2(Screen):

    print(PROJECT_PATH) # will not print

我不知道如何让它在新课程中打印。

标签: pythonclassuser-interfacekivyreturn

解决方案


你需要的是global变量。你知道范围吗?简而言之,全局变量是一种可以从代码文件中的任何位置访问/修改的变量。这是一个示例:

PROJECT_PATH = ""

class TrainNew1(Screen):
    global PROJECT_PATH # this is required to modify the original PROJECT_PATH
    #takes user input,i click a button to submit, runs this function.
    def test(self):
        PROJECT_PATH = self.ids.ProjectName.text 
        #will print PROJECT_PATH fine within test /class function
class TrainNew2(Screen):
    global PROJECT_PATH # this is used to access PROJECT_PATH 
    print(PROJECT_PATH) # Now, It can be used/modified even inside in this class 

推荐阅读