Tkinter :Calculator in Python
import tkinter as tk
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(tk.END, current + number)
def button_clear():
entry.delete(0, tk.END)
def button_equal():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(tk.END, str(result))
except:
entry.delete(0, tk.END)
entry.insert(tk.END, "Error")
def main():
root = tk.Tk()
root.title("Calculator")
entry = tk.Entry(root, width=20, font=("Helvetica", 12))
entry.grid(row=0, column=0, columnspan=4)
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row = 1
col = 0
for button in buttons:
if button == '=':
tk.Button(root, text=button, width=5, command=button_equal).grid(row=row, column=col)
elif button == 'C':
tk.Button(root, text=button, width=5, command=button_clear).grid(row=row, column=col)
else:
tk.Button(root, text=button, width=5, command=lambda b=button: button_click(b)).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
root.mainloop()
if __name__ == "__main__":
main()
No comments:
Post a Comment