I am currently trying to make a GUI Calculator using Qt's PySide2 for python. I started not long ago in PySide2 and only know a few things, but I have run into a problem. First off, I need to send a method named add_item a value when a button is pressed. In Qt or PySide2 you are not able to do this, but using lambda you can. Because I have a lot of buttons I have found it is a lot of copy and pasted code as well as redundant to just say connect, connect, connect, 25 times. So I have decided to use for loops to iterate through the buttons, create them, and connect them. The problem is that when I connect them they all end up with the last values' value. I have tried multiple different ways of looping as well as google, but to no avail. I have searched here on stack overflow and I found 2 examples, but I am unable to understand them. Here is the main code.
numbers_and_actions_list = ["1", "4", "7", "0", "=",
"2", "5", "8", ".", "clear",
"3", "6", "9", "root", "del",
"+", "-", "*", "/", "^"]
buttons_list = []
for value in numbers_and_actions_list:
buttons_list.append(QtWidgets.QPushButton(value))
lambda_button_list = []
for item in numbers_and_actions_list:
lambda_button_list.append(lambda: self.add_item(item))
index = 0
for button in buttons_list:
button.clicked.connect(lambda_button_list[index])
index += 1
Any help would be great. I started python about 2 months ago, so any bad practices that I do please enlighten me so I can become better. Anyways any insights as to what I have done wrong would be amazing, thanks! :D