You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.3 KiB

11 months ago
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def plot_function(func_str, num_points, step, multiplier, x_func):
try:
x_values = np.linspace(x_func[0], x_func[1], num_points)
func = lambda x: eval(func_str)
y_values = func(x_values * multiplier)
ax.clear()
ax.plot(x_values, y_values, label=f'{func_str} ({x_func[0]} to {x_func[1]})')
ax.legend()
canvas.draw()
except Exception as e:
print(f"Error: {e}")
def on_update():
try:
func_str = entry_function.get()
num_points = int(entry_num_points.get())
step = float(entry_step.get())
multiplier = float(entry_multiplier.get())
x_func = [float(entry_x_start.get()), float(entry_x_end.get())]
plot_function(func_str, num_points, step, multiplier, x_func)
except ValueError:
pass
# 创建主窗口
root = tk.Tk()
root.title("Function Plotter")
# 创建图形区域
fig, ax = plt.subplots(figsize=(5, 4))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.grid(row=0, column=1, rowspan=10)
# 添加控件
tk.Label(root, text="Function:").grid(row=0, column=0)
entry_function = tk.Entry(root)
entry_function.grid(row=0, column=1)
entry_function.insert(0, "np.sin(x)")
tk.Label(root, text="Number of Points:").grid(row=1, column=0)
entry_num_points = tk.Entry(root)
entry_num_points.grid(row=1, column=1)
entry_num_points.insert(0, "100")
tk.Label(root, text="Step Size:").grid(row=2, column=0)
entry_step = tk.Entry(root)
entry_step.grid(row=2, column=1)
entry_step.insert(0, "0.1")
tk.Label(root, text="Multiplier:").grid(row=3, column=0)
entry_multiplier = tk.Entry(root)
entry_multiplier.grid(row=3, column=1)
entry_multiplier.insert(0, "1.0")
tk.Label(root, text="X Start:").grid(row=4, column=0)
entry_x_start = tk.Entry(root)
entry_x_start.grid(row=4, column=1)
entry_x_start.insert(0, "-10.0")
tk.Label(root, text="X End:").grid(row=5, column=0)
entry_x_end = tk.Entry(root)
entry_x_end.grid(row=5, column=1)
entry_x_end.insert(0, "10.0")
update_button = tk.Button(root, text="Update Plot", command=on_update)
update_button.grid(row=6, column=0, columnspan=2)
# 初始绘制
on_update()
# 运行主循环
root.mainloop()