-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractice101.py
More file actions
51 lines (41 loc) · 1.25 KB
/
practice101.py
File metadata and controls
51 lines (41 loc) · 1.25 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
import tkinter as tk
def on_button_click(value):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(tk.END, current + str(value))
def on_clear():
entry.delete(0, tk.END)
def on_equals():
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 the main window
root = tk.Tk()
root.title("Simple Calculator")
# Entry widget for display
entry = tk.Entry(root, width=20, font=('Arial', 14), justify='right')
entry.grid(row=0, column=0, columnspan=4)
# Define button layout and create buttons
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row_val = 1
col_val = 0
for button in buttons:
tk.Button(root, text=button, padx=20, pady=20, font=('Arial', 14),
command=lambda b=button: on_button_click(b) if b != '=' else on_equals()).grid(row=row_val, column=col_val)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1
# Clear button
tk.Button(root, text='C', padx=20, pady=20, font=('Arial', 14), command=on_clear).grid(row=row_val, column=col_val)
# Run the GUI
root.mainloop()