2

我正在使用 Python 3.3 和 PyQt 4.10.1。下图来自PyQt book

假设有 5 个按钮,如下所示。单击每个按钮时,它们会将标签的文本更改为包含其按钮编号的上下文。例如,当用户单击带有标题“四”的按钮时,它会将标签更改为You clicked button 'Four'

在此处输入图像描述

不是为每个按钮创建一个信号槽,而是创建一个接受参数和partial()方法的通用方法:

    ...
    self.label = QLabel("Click on a button.")
    self.button1 = QPushButton("One")
    ...
    self.button5 = QPushButton("Five")
    self.connect(self.button1, SIGNAL("clicked()")
                                , partial(self.anyButton, "One"))
    ...
    self.connect(self.button5, SIGNAL("clicked()")
                                , partial(self.anyButton, "Five"))
    ...

def anyButton(self, buttonNumber):
    self.label.setText("You clicked button '%s'" % buttonNumber)

每当我想更改partial(self.anyButton, "One")为 时self.anyButton("One"),都会收到如下错误。

Traceback (most recent call last):
  File "C:\Users\abdullah\Desktop\test.py", line 47, in <module>
    form = Form()
  File "C:\Users\abdullah\Desktop\test.py", line 20, in __init__
    , self.anyButton("One"))
TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoC
onnection): argument 3 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnecti
on): argument 3 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection
): argument 3 has unexpected type 'NoneType'

这是什么原因?为什么我不能直接调用该函数?另外,为什么partial()方法有效?

4

1 回答 1

4

partial返回参数被替换的函数。 anyButton

self.anyButton("One")为您提供函数返回的值。

于 2013-06-08T10:55:33.063 回答