|
|
import tkinter as tk
from tkinter import messagebox
import math
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]
plt.rcParams["axes.unicode_minus"] = False
root = tk.Tk()
root.title("科学计算器")
root.geometry("400x600")
root.resizable(False, False)
root.config(bg="#e5e5e5")
show_text = tk.StringVar()
def add_char(c):
show_text.set(show_text.get() + c)
def clear_all():
show_text.set("")
def backspace():
s = show_text.get()
show_text.set(s[:-1])
def calculate():
try:
expr = show_text.get()
safe_math = {
"sin":math.sin, "cos":math.cos, "tan":math.tan,
"sqrt":math.sqrt, "log":math.log10, "ln":math.log,
"pi":math.pi, "e":math.e
}
res = eval(expr, {"__builtins__":None}, safe_math)
show_text.set(str(round(res, 6)))
except:
show_text.set("输入格式错误")
def factorial():
try:
n = float(show_text.get())
if not n.is_integer():
show_text.set("阶乘必须是整数")
return
n = int(n)
if n < 0:
show_text.set("不能为负数")
else:
show_text.set(str(math.factorial(n)))
except:
show_text.set("输入有误")
def draw_func():
try:
func = show_text.get().strip()
if not func:
messagebox.showinfo("提示", "请输入函数,例如:sin(x)、x**2、log(x)")
return
x = np.linspace(0.01, 10, 1000)
env = {
"x":x, "np":np,
"sin":np.sin, "cos":np.cos, "tan":np.tan,
"sqrt":np.sqrt, "log":np.log10, "ln":np.log,
"pi":np.pi, "e":np.e
}
y = eval(func, {"__builtins__":None}, env)
plt.figure(figsize=(8,5))
plt.plot(x, y, color="#0078d4", linewidth=2)
plt.grid(True, alpha=0.3)
plt.title(f"y = {func}")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
except:
messagebox.showerror("错误", "写法示例:sin(x) cos(x) x**2")
entry = tk.Entry(
root,
textvariable=show_text,
font=("Microsoft YaHei", 28),
bg="#f7f7f7",
fg="#222222",
bd=0,
relief=tk.FLAT,
justify=tk.RIGHT
)
entry.pack(padx=15, pady=20, fill=tk.X, ipady=15)
button_list = [
["sin","cos","tan","sqrt","π"],
["log","ln","n!","(",")"],
["7","8","9","/","←"],
["4","5","6","*","C"],
["1","2","3","-","绘图"],
["0",".","^","+","="]
]
for row in button_list:
row_frame = tk.Frame(root, bg="#e5e5e5")
row_frame.pack(fill=tk.X, padx=8, pady=3)
for text in row:
if text == "←":
cmd = backspace
elif text == "C":
cmd = clear_all
elif text == "=":
cmd = calculate
elif text == "n!":
cmd = factorial
elif text == "绘图":
cmd = draw_func
elif text == "^":
cmd = lambda: add_char("**")
elif text == "π":
cmd = lambda: add_char("pi")
else:
cmd = lambda t=text: add_char(t)
if text in ["sin","cos","tan","sqrt","log","ln","n!","π"]:
bg_col = "#757575"
fg_col = "white"
elif text in ["C", "←"]:
bg_col = "#d1d1d1"
fg_col = "#111111"
elif text in "+-*/^()":
bg_col = "#0078d4"
fg_col = "white"
elif text == "绘图":
bg_col = "#0f8b4e"
fg_col = "white"
elif text == "=":
bg_col = "#0063b1"
fg_col = "white"
else:
bg_col = "#f1f1f1"
fg_col = "#222222"
btn = tk.Button(
row_frame,
text=text,
font=("Microsoft YaHei", 11),
bg=bg_col,
fg=fg_col,
bd=0,
relief=tk.FLAT,
width=6,
height=3,
command=cmd
)
btn.pack(side=tk.LEFT, padx=2)
root.mainloop() |
|