首页 > 解决方案 > 从 python 3.x 中的外部文件应用框架?

问题描述

有没有办法将框架从外部模块应用到根窗口。我有 2 个文件:在 a.py 中有一行,我在一个导入b.pyself.root = root()的类中有一个函数, 在 b.py 我有一个类并实例化一个 Frame 以显示在根窗口 中。没有错误,但框架小部件未显示在根窗口中。我尝试在b.py文件中更改 self.frame = Frame(root)rootself.root

例如:

#file 'a'
class Root:
    def __init__(self):
        self.root = root()
        root.title('Hello')
        self.b = None
    def boo(self):
        import b
        self.b = b.A()
Root.boo()

and

#file 'b'
class A:
    def __init__(self):
        self.frame = tk.LabelFrame(self.root)
        self.frame.pack()
    def __a_meth__(self):
        Button(self.frame, text = 'YES')
        Button.pack()

需要做哪些改变?

标签: pythonpython-3.xclassooptkinter

解决方案


通常你会传入任何需要的东西:

#file 'a'
class Root:
    def __init__(self):
        self.root = root()
        self.root.title('Hello')
        self.b = None
    def boo(self):
        import b
        self.b = b.A(self.root) # pass the root object in
        self.b.__a_meth__() # don't forget to call this if you want to see anything
Root.boo()

#file 'b'
class A:
    def __init__(self, root):
        self.root = root
        self.frame = tk.LabelFrame(self.root)
        self.frame.pack()
    def __a_meth__(self):
        Button(self.frame, text = 'YES')
        Button.pack()

推荐阅读