当把一组按钮的几个点击信号连接到一个带参数的槽函数时,我遇到了一个信号槽的问题。
替换代码0】和
functools.partial
可以用在以下方面。
user = "user"
button.clicked.connect(lambda: calluser(name))
from functools import partial
user = "user"
button.clicked.connect(partial(calluser, name))
而在某些情况下,它们的表现是不同的。
下面的代码显示了一个例子,它期望在点击每个按钮的时候打印出它的文本。
但是当使用lambda方法时,输出结果总是 "button 3"。而partial的方法则是我们所期望的。
我怎样才能找到他们的差异?
from PyQt5 import QtWidgets
class Program(QtWidgets.QWidget):
def __init__(self):
super(Program, self).__init__()
self.button_1 = QtWidgets.QPushButton('button 1', self)
self.button_2 = QtWidgets.QPushButton('button 2', self)
self.button_3 = QtWidgets.QPushButton('button 3', self)
from functools import partial
for n in range(3):
bh = eval("self.button_{}".format(n+1))
# lambda method : always print `button 3`
# bh.clicked.connect(lambda: self.printtext(n+1))
bh.clicked.connect(partial(self.printtext, n+1))
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button_1)
layout.addWidget(self.button_2)
layout.addWidget(self.button_3)
def printtext(self, n):
print("button {}".format(n));
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Program()
window.show()
sys.exit(app.exec_())
Personly, I agree that ButtonGroup method from the accepted answer is the right&elegant solution to this type of issue.
这里有一些关于这个问题的参考资料。