当前位置:网站首页>When using lambda to pass parameters in a loop, the parameters are always the same value

When using lambda to pass parameters in a loop, the parameters are always the same value

2022-07-06 11:24:00 imxlw00

When I use PyQt5 when , You need to pass in parameters when calling events , So I thought of lambda function , The code is as follows :

  for i, button in enumerate(self.button_dict.values()):
       button.clicked.connect(lambda: self.click_checkbox(i))

here i It's all the same value .

lambda function ( Or closure ) What is passed is not the value of the parameter , It is the physical address of the parameter , therefore lambda The parameters passed will all be the same value . If you want to solve it, you can use functools modular .

Solution
Import functools modular , Use partial Method . The changed code is as follows :

button.clicked.connect(partial(self.click_checkbox, i))

Reference resources :https://blog.csdn.net/qq_34965596/article/details/100579458

原网站

版权声明
本文为[imxlw00]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912503177.html