I'm pretty new to programming in general, and have been learning the basics of Python. I wanted to learn some GUI stuff so I looked into some tutorials on using tkinter. I'm following along with this tutorial to create a simple calculator right now: https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/
Towards the bottom of the code, they create all the calculator buttons individually. I thought it would be cleaner and easier to create a function and use a for-loop to run through and create each button. It works fine except when I press the buttons they only update the entry field to the "/" symbol, the last index of my buttons tuple. Any ideas why this could be happening? Full code below:
import tkinter as tk
def create_buttons():
"""
adds calculator buttons in a for loop, resetting column and row when max is hit
"""
buttons = ("1","2","3","+","4","5","6","-","7","8","9","*", "Clear", "0", "=", "/")
column = 0
row = 2
for i in buttons:
new_button = tk.Button(calc, text=i, fg="black", bg="red", height=2, width=10, command=lambda: press(i))
new_button.grid(column=column, row=row)
if column == 3:
column = 0
row += 1
else:
column += 1
def press(button):
equation.set(button)
if __name__ == "__main__":
calc = tk.Tk()
calc.title("Calculator")
calc.geometry("400x300")
calc.configure(background="light green")
equation = tk.StringVar()
expression_field = tk.Entry(calc, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=130)
create_buttons()
calc.mainloop()
(I know the calculator doesn't actually do anything yet, I just wanted to test that this was working and got stuck here.)