Skip to content

Instantly share code, notes, and snippets.

@AliAlmasi
Created August 22, 2022 21:23
Show Gist options
  • Save AliAlmasi/8cc9535a73bd8f5bcf719e10599fc4a6 to your computer and use it in GitHub Desktop.
Save AliAlmasi/8cc9535a73bd8f5bcf719e10599fc4a6 to your computer and use it in GitHub Desktop.
Python tkinter Calculator
import tkinter as tk
def buttonpressed(i):
if i != '=':
entry.insert(tk.END, i)
else:
expression = entry.get()
try:
value = eval(expression)
new_string = f'{value: ,}'
entry.delete(0, tk.END)
entry.insert(0, new_string)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, e)
root = tk.Tk()
root.title = 'Python Calculator'
entry = tk.Entry(root, width=26, borderwidth=5, font=('Consolas', 12))
entry.grid(row=0, column=0, padx=10, pady=10, columnspan=5)
btn_frame = tk.Frame(root, width=40, height=100)
btn_frame.grid(row=1, columnspan=5)
buttonText = ['7', '8', '9', '/', '*', '4', '5', '6', '-', '+', '0', '1', '2', '3', '=']
i = j = 0
for x in buttonText:
b = tk.Button(btn_frame, width=5, text=x, command= lambda x = x: buttonpressed(x))
b.grid(row=i, column=j, ipadx=2, ipady=4)
j+=1
if j == 5:
i+=1
j = 0
del_btn = tk.Button(root, text='Clear', width=30, command= lambda: entry.delete(0, tk.END))
del_btn.grid(row=2, columnspan=5, ipadx=5, ipady=4)
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment