【问题标题】:How to import a variable that is in a class, from one file to another?如何将类中的变量从一个文件导入另一个文件?
【发布时间】:2018-01-10 12:25:32
【问题描述】:

文件 1

#file1
from tkinter import *

class UI:
    def __init__(self):
        self.main_window = Tk()
        sam = 'TestWord'
        import file2

    def run(self):
        self.main_window.mainloop()    

def main():
    ui = UI()
    ui.run()

main()

文件 2

#file2
from file1 import sam
print(sam)

输出

from file1 import sam
builtins.ImportError: cannot import name 'sam'

如何在课堂上导入 sam?我知道如何在没有课堂的情况下做到这一点。此外,这段代码打开了两个 GUI,这一定是问题的一部分,但我现在完全迷失了。两个变量都必须是 self.sam 吗?因此,self.sam = 'TestWord' 并导入 self.sam。我已经尝试过了,但它没有用,但是,我可能在这里遗漏了一个细节。任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x file class tkinter python-import


    【解决方案1】:

    问题是import file2 不会为您运行代码。它只发生在 python REPL 上。

    您可以执行以下操作,

    文件 1:

    from tkinter import *
    
    class UI:
        def __init__(self):
            self.main_window = Tk()
            sam = 'TestWord'
            from file2 import foo
            foo(sam)
    
        def run(self):
            self.main_window.mainloop()    
    
    def main():
        ui = UI()
        ui.run()
    
    main()
    

    文件2:

    def foo(sam):
        print(sam)
    

    【讨论】:

      【解决方案2】:

      所以你的main()在你导入file1时不会运行,只有在你运行file1时才使用

      if __name__ == '__main__':
          main()
      

      此外,您无法在类内部访问sam,在这种情况下,这不是文件问题,要从类外部访问它,您需要将其设为全局,或者使用self.sam = ... 并拥有你的类的一个实例。

      更好的是让 file2 包含使用您导入到 file1 中的 sam 值的方法。

      在没有看到您的实际用例的情况下,我无法提供任何其他方法来实现您想要的,但您确实不应该将其设为全局以从另一个文件访问。

      【讨论】:

        猜你喜欢
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 2013-06-19
        • 1970-01-01
        • 2021-04-17
        • 1970-01-01
        相关资源
        最近更新 更多