電卓のコード
電卓.py
import tkinter as tk
import math
class AdvancedCalculator(tk.Tk):
def __init__(self):
super().__init__()
self.title("Advanced Calculator")
self.geometry("400x600")
self.result_var = tk.StringVar()
# エントリウィジェット
entry = tk.Entry(self, textvariable=self.result_var, font=('Helvetica', 20), justify='right')
entry.grid(row=0, column=0, columnspan=5, padx=10, pady=10, ipadx=8, ipady=8)
# ボタンのレイアウト
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),
('sqrt', 5, 0), ('C', 5, 1), ('^', 5, 2), ('(', 5, 3),
(')', 6, 0), ('sin', 6, 1), ('cos', 6, 2), ('tan', 6, 3),
('log', 7, 0), ('exp', 7, 1), ('!', 7, 2), ('π', 7, 3),
]
for (text, row, col) in buttons:
tk.Button(self, text=text, padx=20, pady=20, font=('Helvetica', 14),
command=lambda t=text: self.button_click(t)).grid(row=row, column=col)
def button_click(self, value):
current = self.result_var.get()
if value == '=':
try:
result = eval(current)
self.result_var.set(result)
except Exception as e:
self.result_var.set("Error")
elif value == 'C':
self.result_var.set("")
elif value == 'sqrt':
try:
result = math.sqrt(eval(current))
self.result_var.set(result)
except Exception as e:
self.result_var.set("Error")
elif value == '!':
try:
result = math.factorial(int(eval(current)))
self.result_var.set(result)
except Exception as e:
self.result_var.set("Error")
elif value == 'π':
self.result_var.set(current + str(math.pi))
else:
self.result_var.set(current + str(value))
if __name__ == "__main__":
app = AdvancedCalculator()
app.mainloop()
以上です☆