[英]Create pyqt5 pushbuttons with click event using loop
How Can I Create PushButtons With connect using loop如何使用循环连接创建按钮
list = ['apple','orange','banana','carrot']
for i,s in enumerate(list)
list[i] = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
list[i].setText(s[0])
list[i].clicked.connect(lambda:getbuttontext(list[i].text()))
and Here Is getbuttontext function:这是getbuttontext函数:
def getbuttontext(n):
print(n)
My Problem Is That When I Click On Any button the Function print "carrot" How To Fix It Please...
我的问题是,当我单击任何按钮时,功能打印“胡萝卜”如何修复它请...
The solution is simple, define the input parameters of the lambda function:解决方法很简单,定义lambda函数的输入参数:
fruits = ['apple','orange','banana','carrot']
for i,s in enumerate(fruits)
btn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
btn.setText(s[0])
btn.clicked.connect(lambda checked, text=s : getbuttontext(text))
Note: I put checked because it is the parameter that passes the clicked signal by default.注意:我放了checked,因为它是默认传递clicked信号的参数。
lambda doesnt store the value of button ,instead you can use another method lambda 不存储按钮的值,而是您可以使用另一种方法
from functools import partial
for i in range(10):
btn[i].clicked.connect(patial(getbuttontext,btn[i].text()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.