app = tk.Tk() app.title("Calculator") app.geometry("300x400") app.resizable(False, False)
expression = ""
- Function to update expression
def press(num):
global expression expression += str(num) equation.set(expression)
- Function to clear screen
def clear():
global expression
expression = ""
equation.set("")
- Function to calculate result
def equal():
global expression
try:
result = str(eval(expression))
equation.set(result)
expression = result
except:
equation.set("Error")
expression = ""
- StringVar for display
equation = tk.StringVar()
- Display screen
display = tk.Entry(app, textvariable=equation, font=('Arial', 20), bd=10, relief='sunken', justify='right') display.pack(fill='x', padx=10, pady=10)
- Buttons frame
frame = tk.Frame(app) frame.pack()
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3)
]
for (text, row, col) in buttons:
if text == '=':
btn = tk.Button(frame, text=text, width=5, height=2, font=('Arial', 14), command=equal)
else:
btn = tk.Button(frame, text=text, width=5, height=2, font=('Arial', 14), command=lambda t=text: press(t))
btn.grid(row=row, column=col, padx=5, pady=5)
- Clear button
clear_btn = tk.Button(app, text='C', font=('Arial', 14), height=2, command=clear) clear_btn.pack(fill='x', padx=10, pady=5)
Talk pages are where people discuss how to make content on Wikipedia the best that it can be. You can use this page to start a discussion with others about how to improve the "File:Python-logo-notext.svg" page.