我是 python 和 PyQt 的新手,正在使用它開發我的第一個應用程序,但在嘗試實例化我再次創建的類時遇到了問題。我有以下錯誤:Traceback (most recent call last): File "ConfiguradorAnx.py", line 16, in <lambda> self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct))TypeError: 'InfoProduct' object is not callableAborted代碼是這樣的:from PyQt5 import QtCore, QtGui, QtWidgets, uicimport sysclass StartWindow(QtWidgets.QMainWindow): #This function should inherit the class #used to make the ui file def __init__(self): super(StartWindow,self).__init__() #Calling the QMainWindow constructor uic.loadUi('Janela_inicial.ui',self) #defining quit button from generated ui self.QuitButton = self.findChild(QtWidgets.QPushButton, 'QuitButton') self.QuitButton.clicked.connect(QtCore.QCoreApplication.instance().quit) #defining product info button self.ProductInfo = self.findChild(QtWidgets.QPushButton, 'ProductInformation') self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct)) self.show() #Show the start window def newWindow(self, _class): self.newWindow = _class() del self.newWindowclass InfoProduct(QtWidgets.QMainWindow): def __init__(self): super(InfoProduct,self).__init__() uic.loadUi('informacao_prod.ui',self) self.QuitButton = self.findChild(QtWidgets.QPushButton, 'pushButton') self.QuitButton.clicked.connect(lambda: self.destroy()) self.show()def main(): app = QtWidgets.QApplication(sys.argv) #Creates a instance of Qt application InitialWindow = StartWindow() app.exec_() #Start applicationif __name__ == '__main__': main()我第一次點擊self.ProductInfo按鈕時它起作用了,InfoProduct 窗口打開了,但是當我關閉窗口并再次點擊同一個按鈕時,我遇到了錯誤。我不知道我想念的是什么,我希望你們能幫忙!干杯!
1 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
您在newWindow
執行時覆蓋了該函數:
def newWindow(self, _class): self.newWindow = _class()
通過這樣做,結果是下次您單擊該按鈕時,lambda 將嘗試調用self.newWindow(InfoProduct)
,但此時self.newWindow
是 的實例InfoProduct
,這顯然是不可調用的。
解決方案很簡單(也很重要),為指向實例的函數和變量使用不同的名稱:
self.ProductInfo.clicked.connect(lambda: self.createNewWindow(InfoProduct)) def createNewWindow(self, _class): self.newWindow = _class()
兩個小旁注:
沒有必要使用
findChild
, 因為loadUi
已經為小部件創建了 python 實例屬性:您已經可以訪問self.QuitButton
,等等。避免對變量和屬性使用大寫名稱。在Python 代碼樣式指南(又名 PEP-8)中閱讀有關此內容和其他代碼樣式建議的更多信息。
添加回答
舉報
0/150
提交
取消