use*_*862 1 python lambda qpushbutton pyqt5
当我运行下面的代码时,它显示如下。为什么 x 不是“x”而是变成布尔值?这种情况仅发生在传递到用 lambda 调用的函数中的第一个参数上。
假 y /home/me/model/some_file
from PyQt5.QtWidgets import QPushButton
modelpath = '/home/me/model'
filelist = os.listdir(modelpath)
x = 'x'
y = 'y'
def HelloWidget(QWidget):
def __init__(self):
for file in filelist:
button = QPushButton(file)
button.clicked.connect(lambda x=x,y=y,file=file: self.myfunction(x,y,file)
def myfunction(self,x,y,file):
print(x)
print(y)
print(file)
Run Code Online (Sandbox Code Playgroud)
该问题是因为clicked传递了一个布尔值来指示是否已检查而引起的。适当的事情是使用参数来使用该参数:
button.clicked.connect(lambda checked, x=x,y=y,file=file: self.myfunction(x,y,file))
Run Code Online (Sandbox Code Playgroud)