We can create a simple calculator with a graphical interface using the tkinter library in Python.
Here's an example of how to do it:
import tkinter as tk
def on_click(button_text):
if button_text == "=":
try:
result = eval(display_var.get())
display_var.set(result)
except:
display_var.set("Error")
elif button_text == "C":
display_var.set("")
else:
current_expression = display_var.get()
display_var.set(current_expression + button_text)
# Create the main application window
app = tk.Tk()
app.title("Simple Calculator")
# Variable to store the expression being entered
display_var = tk.StringVar()
display_var.set("")
# Create the display area for the calculator
display = tk.Entry(app, textvariable=display_var, font=("Helvetica", 20), bd=10, justify="right")
display.grid(row=0, column=0, columnspan=4)
# Create buttons for numbers and operators
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
]
# Create and place the buttons in the grid
row_num = 1
col_num = 0
for button_text in buttons:
button = tk.Button(app, text=button_text, font=("Helvetica", 20), padx=20, pady=10, command=lambda text=button_text: on_click(text))
button.grid(row=row_num, column=col_num)
col_num += 1
if col_num > 3:
col_num = 0
row_num += 1
# Start the main event loop
app.mainloop()
Save the above code in a Python file (e.g., calculator.py) and run it. It will launch a simple calculator with a graphical interface. You can perform basic arithmetic calculations by clicking the buttons. Press "C" to clear the display, and "=" to evaluate the expression.
Note that this example assumes the user enters a valid expression, and the eval() function is used to evaluate the expression. In a real-world application, you may want to implement error handling and validation to ensure safe input handling.