【问题标题】:Error when instantiating a class for the second time第二次实例化类时出错
【发布时间】:2020-09-20 22:37:14
【问题描述】:

我是 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 callable
Aborted

代码如下:

from PyQt5 import QtCore, QtGui, QtWidgets, uic
import sys

class 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.newWindow

class 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 application

if __name__ == '__main__':
    main()

我第一次单击self.ProductInfo 按钮时它可以工作并且InfoProduct 窗口打开,但是当我关闭窗口并再次单击同一个按钮时,我遇到了错误。我无法弄清楚我错过了什么,希望你们能提供帮助!

干杯!

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 python-3.5


    【解决方案1】:

    您在执行过程中覆盖了newWindow 函数:

    def newWindow(self, _class):
        self.newWindow = _class()
    

    这样做的结果是,下次单击按钮时,lambda 会尝试调用self.newWindow(InfoProduct),但此时self.newWindowInfoProduct 的实例,显然不可调用。

    解决方案很简单(并且非常重要)为函数和指向实例的变量使用不同的名称:

            self.ProductInfo.clicked.connect(lambda: self.createNewWindow(InfoProduct))
    
        def createNewWindow(self, _class):
            self.newWindow = _class()
    

    两个小注:

    • 没有必要使用findChild,因为loadUi已经为小部件创建了python实例属性:你已经可以访问self.QuitButton等。
    • 避免对变量和属性使用大写的名称。在 Style Guide for Python Code(又名 PEP-8)上阅读有关此和其他代码样式建议的更多信息。

    【讨论】:

    • 非常感谢您的解释,真的解决了。另外,附注非常有用,现在就去阅读风格指南。
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2021-01-04
    • 2015-01-02
    • 1970-01-01
    • 2015-04-30
    • 2016-06-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多