Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.0 kB
2
Indexable
Never
import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Calculator")

# Set the window size
root.geometry("400x500")

# Global variable to store the expression
expression = ""

# Function to update the expression in the input field
def press(num):
    global expression
    expression += str(num)
    equation.set(expression)

# Function to evaluate the expression
def equal_press():
    try:
        global expression
        # Evaluate the expression
        total = str(eval(expression))
        equation.set(total)
        expression = ""
    except:
        equation.set(" error ")
        expression = ""

# Function to clear the input field
def clear():
    global expression
    expression = ""
    equation.set("")

# Create the input field
equation = tk.StringVar()
input_field = tk.Entry(root, textvariable=equation, font=('arial', 20, 'bold'), bd=10, insertwidth=4, width=14, borderwidth=4)
input_field.grid(columnspan=4)

# Create buttons for the calculator
buttons = [
    '7', '8', '9', '/', 
    '4', '5', '6', '*', 
    '1', '2', '3', '-', 
    'C', '0', '=', '+'
]

# Create buttons and place them on the grid
row_val = 1
col_val = 0

for button in buttons:
    if button == "=":
        btn = tk.Button(root, text=button, padx=20, pady=20, font=('arial', 18, 'bold'), command=equal_press)
    elif button == "C":
        btn = tk.Button(root, text=button, padx=20, pady=20, font=('arial', 18, 'bold'), command=clear)
    else:
        btn = tk.Button(root, text=button, padx=20, pady=20, font=('arial', 18, 'bold'), command=lambda x=button: press(x))
    
    btn.grid(row=row_val, column=col_val, sticky="nsew")
    col_val += 1
    if col_val > 3:
        col_val = 0
        row_val += 1

# Make the grid cells expandable
for i in range(4):
    root.grid_columnconfigure(i, weight=1)
for i in range(5):
    root.grid_rowconfigure(i, weight=1)

# Start the application
root.mainloop()
Leave a Comment