TypeError:接受缺少2个必需参数(仍然有效)

时间:2013-12-04 16:10:14

标签: python python-3.x pyqt pyqt4

这是一个好奇心问题。我有一块代码块在accepted.connect()上执行。 它抛出了这个错误但是当我检查结果时它们仍然可以工作。根据我从按钮框中理解的内容:按OK或取消后,对话框应自行关闭。我甚至没有初始化self.buttonBox.canceled.connect但是当我按下取消时窗口关闭。当我按下OK然后窗口保持打开并出现以下错误:

TypeError: accept() missing 2 required positional arguments: 'player' and 'window'

所以这里有一些代码:

class UIinit(QtGui.QDialog, UI.Buy_Cargo.Ui_Dialog):
        """The Dialog for initiation"""
        def __init__(self, player, window):
            super(UIinit, self).__init__()
            self.window = window
            self.player = player
            self.setupUi(self)
            #for i in Config.port_prices:
            #   up = getattr(self, "btn_" + i + "_up")
            #    up.clicked.connect(partial(self.up, i, player))
            #    down = getattr(self, "btn_" + i + "_down")
            #    down.clicked.connect(partial(self.down, i))
            #    add_price = getattr(self, "H_" + i)
            #    add_price.setText(i +
            #        " (" + str(self.player.port.price[i]) + ")")
            self.buttonBox.accepted.connect(  # the important part
                partial(self.accept, player, window))
        def accept(self, player, window):
            if int(self.V_Total.text()) <= player.money:
                for i in player.ship.cargo:
                    num = int(getattr(self, "V_" + i).text())
                    player.ship.cargo[i] += num
                window.to_shipyard()
dia = UIinit(player, window)
dia.exec_()

我尝试过connect(lambda:self.accept(player,window))并使用self.player和self.window作为参数。

2 个答案:

答案 0 :(得分:3)

下面这个简化的片段确实按预期工作,因此您的问题在其他地方。只是一个狂野的想法 - 如果你复制/粘贴你的代码,其中有标签,如果你有混合的标签和空格,你可以得到非常奇怪的结果 - 比如在def accept中实际定义__init__本身而不是一个正确的方法,在这种情况下self不会自动传递给函数。与您的错误消息不符,但可能值得检查....

from functools import partial

class Button(object):
    def __init__(self):
        self.callbacks = []
    def connect(self, callback):
        self.callbacks.append(callback)
    def click(self):
        for callback in self.callbacks:
            callback()

class UI(object):
    """The Dialog for initiation"""
    def __init__(self, player, window):
        self.window = window
        self.player = player
        self.button = Button()
        self.button.connect(  # the important part
            partial(self.accept, player, window))
        self.button.connect( 
            lambda: self.accept(player, window))

    def accept(self, player, window):
        print "accept %s %s" % (player, window)

    def exec_(self):
        self.button.click()
player = "p"
window = "w"
dia = UI(player, window)
dia.exec_()

答案 1 :(得分:1)

它似乎与我覆盖对话框的接受功能有关。一旦我将accept()更改为GoNinjaGoNinjaGo(),一切正常。