亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

第二次實例化類時出錯

第二次實例化類時出錯

慕標琳琳 2022-12-20 15:13:41
我是 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)中閱讀有關此內容和其他代碼樣式建議的更多信息。


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號