File talk:Python-logo-notext.svg

app = tk.Tk() app.title("Calculator") app.geometry("300x400") app.resizable(False, False)

expression = ""

  1. Function to update expression

def press(num):

   global expression
   expression += str(num)
   equation.set(expression)
  1. Function to clear screen

def clear():

   global expression
   expression = ""
   equation.set("")
  1. Function to calculate result

def equal():

   global expression
   try:
       result = str(eval(expression))
       equation.set(result)
       expression = result
   except:
       equation.set("Error")
       expression = ""
  1. StringVar for display

equation = tk.StringVar()

  1. 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)

  1. 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)
  1. 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)

Start a discussion