在Python中导入值

rec*_*gle 2 python import class tkinter

我有一个创建窗口的小模块(program1).我把它导入了我的另一个python程序(program2).

如何使程序2获得self.x和x在program1中?

这是program1.

import Tkinter

class Class(Tkinter.Tk):

    def __init__(self, parent):

        Tkinter.Tk.__init__(self, parent)
        self.parent = parent

        self.Main()

    def Main(self):
        self.button= Tkinter.Button(self,text='hello')
        self.button.pack()

        self.x = 34
        x = 62





def run():
    app = Class(None)
    app.mainloop()

if __name__ == "__main__":
    run()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您可以将变量self.x作为以下实例的成员来访问Class:

c = Class(parent)
print(c.x)
Run Code Online (Sandbox Code Playgroud)

您无法访问本地变量 - 当方法调用结束时,它超出范围.