简体   繁体   English

python中部分函数的参数

[英]arguments for partial function in python

I have a function defined like this: 我有一个像这样定义的函数:

def func(self, boolVal):

and I want to create a connection between QPushButton() and this function like this: 我想在QPushButton()和这个函数之间创建一个连接,如下所示:

self.button1.clicked.connect(partial(self.func, False))

when I run this, it tells me that func() takes exactly 2 arguments (3 given) anyone knows why this could happened? 当我运行它时,它告诉我func()需要2个参数(给出3个),任何人都知道为什么会发生这种情况?

functools.partial works fine. functools.partial工作正常。

See following example: 请参阅以下示例:

from functools import partial
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.button = QPushButton('test', parent=self)
        self.button.clicked.connect(partial(self.func, False))
        self.button.show()
    def func(self, boolVar):
        print boolVar

app = QApplication([])
win = MyWindow()
win.show()
app.exec_()

If you still get error replace func signature with: 如果仍然出现错误,请将func签名替换为:

def func(self, boolVar, checked):
    print boolVar

The first argument is the self parameter, which is bound when you write self.func . 第一个参数是self参数,它在您编写self.func时绑定。 The second argument is the False you supplied to partial , so when Qt calls it with a third bool checked parameter from QPushButton.clicked you end up with 3 arguments. 第二个参数是你提供给partialFalse ,所以当Qt用QPushButton.clicked的第三个bool checked参数调用它时,你最终得到3个参数。

Just write: 写吧:

self.button1.clicked.connect(self.func)

However, the checked parameter is optional so func should be defined as: 但是, checked参数是可选的,因此func应定义为:

def func(self, checked=False):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM