【问题标题】:apply frame from external file in python 3.x?从 python 3.x 中的外部文件应用框架?
【发布时间】:2021-01-11 04:38:48
【问题描述】:

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

需要做哪些改变?

【问题讨论】:

  • 肯定有错误,因为self.rootA.__init__() 中未定义。
  • 谢谢,我知道了。错误是我将调用分配给了一个变量。

标签: python python-3.x class oop tkinter


【解决方案1】:

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

#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()

【讨论】:

  • 我试过了,但框架没有打包在根窗口中。
  • 您需要出示minimal reproducible example 以便我们提供帮助。
  • 抱歉,谢谢,我想通了。错误是我没有传递对象并将其分配给变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 2016-05-10
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
相关资源
最近更新 更多