【问题标题】:TypeError: closeEvent() takes exactly 4 arguments (2 given)TypeError: closeEvent() 正好需要 4 个参数(给定 2 个)
【发布时间】:2019-08-02 17:29:27
【问题描述】:

我正在尝试创建一个仅从另一种方法打印 a、b、c 的 GUI。我想将此方法与类分开,因为它将进入另一个脚本。当我运行它时,它会打印出正确的结果;但是,它也给出了错误。代码:

from PyQt4 import QtGui
import sys

def printStuff(a, b, c):
    print a, b, c

class Login(QtGui.QDialog):

    def __init__(self,a,b,c):
        super(Login, self).__init__()
        self.buttonLogin = QtGui.QPushButton('Print Stuff', self)
        self.buttonLogin.clicked.connect(lambda: self.closeEvent(a,b,c))
        self.grid = QtGui.QGridLayout(self)
        self.setGeometry(650,350,400,150)
        self.setFixedSize(400, 150)

    def closeEvent(self,a,b,c):
        printStuff(a,b,c)
        self.close()

def RunApp(a,b,c):
    app = QtGui.QApplication(sys.argv)
    login = Login(a,b,c)
    login.show()
    app.exec_()

RunApp('1','2','3')

预期结果:1 2 3

实际结果:1 2 3 TypeError: closeEvent() 正好接受 4 个参数(给定 2 个)

这是误报错误吗?我该如何纠正这个问题?

【问题讨论】:

  • 问题是self.buttonLogin.clicked.connect(lambda: self.closeEvent(a,b,c)),所以lambda 可能没有必要。
  • @Carcigenicate,没有踪迹。它所说的只是“TypeError:closeEvent()恰好需要4个参数(2个给定)1 2 3”
  • 您无法选择closeEvent 需要多少参数;无论调用closeEvent 都只会提供一个参数。
  • @DavidCullen,删除 lambda 会导致我的 GUI 在启动时调用 printStuff,即使我没有点击按钮
  • @J.D.是的,正如我们都知道的那样,connect 需要一个不带参数的函数。

标签: python pyqt4


【解决方案1】:

您正在为连接按钮的 closeEvent 提供更多参数。 closeEvent() 将 QCloseEvent 作为参数。

from PyQt4 import QtGui
import sys

def printStuff(a, b, c):
    print a, b, c

class Login(QtGui.QDialog):

    def __init__(self,a,b,c):
        super(Login, self).__init__()
        self.a = a
        self.b = b
        self.c = c
        self.buttonLogin = QtGui.QPushButton('Print Stuff', self)
        self.buttonLogin.clicked.connect(self.closeGUI)
        self.grid = QtGui.QGridLayout(self)
        self.setGeometry(650,350,400,150)
        self.setFixedSize(400, 150)

    def closeGUI(self):
        printStuff(self.a,self.b,self.c)
        self.close()

def RunApp(a,b,c):
    app = QtGui.QApplication(sys.argv)
    login = Login(a,b,c)
    login.show()
    app.exec_()

RunApp('1','2','3')

【讨论】:

  • 嗨@Dress,虽然这消除了错误,但它现在产生了两次结果。还有,为什么事件参数传了却没有使用?
  • ohhhhhhhh,现在更有意义了。非常感谢!
  • @J.D.没问题,如果解决了您的问题,请点赞并标记为已解决。
猜你喜欢
  • 2014-05-31
  • 1970-01-01
  • 2013-04-07
  • 2012-03-15
  • 2014-05-06
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多