从外部fi引用对象

2024-06-26 13:49:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的GUI中,我试图从外部文件向HBox布局添加一个小部件。我想这样做,使我的项目变得更清洁

错误

  Traceback (most recent call last):
  File "__main__.py", line 26, in <module>
    w = GUI()
  File "__main__.py", line 15, in __init__
    frames.stopVerification()
  File "/home/jarno/python/test/frames.py", line 12, in stopVerification
    __main__.w.principalLayout.addWidget(stopVerificationFrame)
AttributeError: module '__main__' has no attribute 'w'

我不明白为什么模块main没有属性w,因为实际上创建了类GUI的实例w

我为您编写了一个简化的代码:

主文件:

from PyQt5.QtWidgets import (QApplication, QFrame, QGridLayout, QHBoxLayout, QPushButton, QVBoxLayout, QWidget)

import frames

class GUI(QWidget):
    def __init__(self, parent=None):
        super(GUI, self).__init__(parent=parent)
        self.principalLayout = QHBoxLayout(self)
        self.controlFrame = QFrame(self) 
        self.gridLayout = QGridLayout(self.controlFrame)
        self.principalLayout.addWidget(self.controlFrame)

        self.widgets()

        frames.stopVerification()
    def widgets(self):
        self.bStart = QPushButton('Start')
        self.gridLayout.addWidget(self.bStart, 0, 0)

        self.bStop = QPushButton('Stop')
        self.gridLayout.addWidget(self.bStop, 0, 2)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)    
    w = GUI()
    w.show()
    sys.exit(app.exec_())

帧文件:

from PyQt5.QtWidgets import (QApplication, QFrame, QGridLayout, QHBoxLayout, QPushButton, QVBoxLayout, QWidget)

import gui

def stopVerification(): 
        stopVerificationFrame = QFrame()
        horizontalLayout = QHBoxLayout(stopVerificationFrame)

        bDesktop = QPushButton("Desktop")
        horizontalLayout.addWidget(bDesktop)

        gui.w.principalLayout.addWidget(stopVerificationFrame)

Tags: 文件pyimportselfframesmainguifile