Repository navigation
Expand file tree
/
Copy pathcalculator.py
More file actions
64 lines (53 loc) · 1.77 KB
/
Copy pathcalculator.py
File metadata and controls
64 lines (53 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import tkinter as tk
# Create the root window
root = tk.Tk()
root.title("Calculator")
# Global variables
expression = ""
# Function to update the display when buttons are pressed
def button_click(value):
global expression
expression += str(value)
display_var.set(expression)
# Function to evaluate the expression
def calculate():
global expression
try:
result = str(eval(expression)) # Evaluate the expression
display_var.set(result)
expression = result # Store result for future calculations
except Exception as e:
display_var.set("Error")
expression = ""
# Function to clear the display
def clear_display():
global expression
expression = ""
display_var.set("")
# Create the display entry with variable
display_var = tk.StringVar()
display = tk.Entry(root, textvariable=display_var, font=("Arial", 20), bd=10, insertwidth=2, width=14, borderwidth=4)
display.grid(row=0, column=0, columnspan=4)
# Create buttons for numbers and operators
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'C', '0', '=', '+'
]
row = 1
col = 0
for button in buttons:
if button == "=":
tk.Button(root, text=button, padx=20, pady=20, font=("Arial", 18), command=calculate).grid(row=row, column=col)
elif button == "C":
tk.Button(root, text=button, padx=20, pady=20, font=("Arial", 18), command=clear_display).grid(row=row, column=col)
else:
tk.Button(root, text=button, padx=20, pady=20, font=("Arial", 18),
command=lambda b=button: button_click(b)).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
# Start the GUI main loop
root.mainloop()