import tkinter as tk def press(x): entry.insert(tk.END, x) def clear(): entry.delete(0, tk.END) def calculate(): try: result = eval(entry.get()) entry.delete(0, tk.END) entry.insert(tk.END, str(result)) except Exception as e: entry.delete(0, tk.END) entry.insert(tk.END, "Error") # Create main window root = tk.Tk() root.title("Simple Calculator") # Display entry = tk.Entry(root, width=30, font=("Arial", 18), bd=5, justify="right") entry.grid(row=0, column=0, columnspan=4, padx=50, pady=10) buttons = [('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('0', 4, 0), ('.', 4, 1), ('+', 4, 2), ('=', 4, 3),] for (text, row, col) in buttons: if text == '=': cmd = calculate else: cmd = press(x) tk.Button(root, text=text, width=5, height=2,command=cmd).grid(row=row, column=col) # Clear button tk.Button(root, text='C', width=22, height=2, font=("Arial", 18), command=clear).grid(row=5, column=0, columnspan=4) root.mainloop() I am trying to write a simple calculator with GUI. ChatGPT is saying I should use the lambda function in the else statement to get cmd = lambda x=textress(x) but I don't understand why. I wanted to assign the function press(x) to cmd so that later when I click the button, it will run whatever function is in the cmd but it seems like the lambda function is required to "wrap it" in a function. Continue reading...