Python QPushButton 列表点击事件处理:数字按钮添加和公式更新
Python QPushButton 列表点击事件处理:数字按钮添加和公式更新
本文将介绍如何在 Python 中使用 QPushButton 列表实现数字按钮的点击事件处理,并向 self.formula 添加数字。
问题描述:
我建立了一个 QPushButton 的列表,希望实现一个槽,当点击按钮 numButton[i] 时,打印 i,并将 i 加入到 self.formula 中。
代码示例:
# 数字按键
numButton = [QPushButton(self) for i in range(10)]
# 0
numButton[0].setText('0')
numButton[0].setGeometry(buttonInitX+buttonSize, buttonInitY-buttonSize, buttonSize, buttonSize)
numButton[0].clicked.connect(self.pushZero)
# 1~9
for i in range(1, 10):
numButton[i].setText(str(i))
numButton[i].setGeometry(buttonInitX+buttonSize*((i-1)%3), buttonInitY+buttonSize*((i-1)//3), buttonSize, buttonSize)
numButton[i].clicked.connect(lambda index=i: self.sl(index))
def sl(self, i):
print(i)
self.formula.append(i)
print(self.formula)
错误分析:
在上面的代码中,lambda 函数内部将参数名命名为 index,但在 sl 函数内部却使用了 i 作为参数名。这种不一致导致了错误的输出结果。
解决方案:
将 sl 函数的参数名修改为 index,并确保在点击按钮时,self.formula 的值没有被修改为 False。
修正后的代码:
# 数字按键
numButton = [QPushButton(self) for i in range(10)]
# 0
numButton[0].setText('0')
numButton[0].setGeometry(buttonInitX+buttonSize, buttonInitY-buttonSize, buttonSize, buttonSize)
numButton[0].clicked.connect(self.pushZero)
# 1~9
for i in range(1, 10):
numButton[i].setText(str(i))
numButton[i].setGeometry(buttonInitX+buttonSize*((i-1)%3), buttonInitY+buttonSize*((i-1)//3), buttonSize, buttonSize)
numButton[i].clicked.connect(lambda index=i: self.sl(index))
def sl(self, index):
print(index)
self.formula.append(index)
print(self.formula)
总结:
在使用 lambda 函数时,要注意参数名的使用,避免与槽函数的参数名不一致导致错误。同时,要确保在点击按钮时,self.formula 的值没有被修改为 False。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qod9 著作权归作者所有。请勿转载和采集!