函数

[up主专用,视频内嵌代码贴在这]

制作这样的软件并不复杂,你可以使用 Python 编程语言和一些库来实现,比如 Tkinter 用于界面设计,matplotlib 用于生成图像。这是一个基本的实现步骤和代码模板,帮助你快速上手:

需求实现步骤

  1. 安装必要的工具和库:

    • Python(推荐安装最新版)。
    • 必要的库:matplotlibtkinter(Python 内置)。
    • 安装 matplotlib 的命令:pip install matplotlib
  2. 软件功能设计:

    • 打开软件后显示一个平面直角坐标系。
    • 允许用户在输入框中输入函数,比如 x**2sin(x)
    • 点击按钮后,图像更新为对应函数的曲线。
  3. 使用 pyinstaller 将 Python 脚本打包成 .exe 程序。


代码模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import tkinter as tk
from tkinter import messagebox
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def plot_function():
try:
# 获取输入的函数表达式
func_str = entry.get()
# 定义自变量范围
x = np.linspace(-10, 10, 500)
# 计算对应的函数值
y = eval(func_str)
# 清除旧图像
ax.clear()
# 绘制新图像
ax.plot(x, y, label=f"y = {func_str}")
ax.axhline(0, color="black", linewidth=0.5)
ax.axvline(0, color="black", linewidth=0.5)
ax.grid(True)
ax.legend()
canvas.draw()
except Exception as e:
messagebox.showerror("错误", f"无效的函数表达式:{e}")

# 创建主窗口
root = tk.Tk()
root.title("函数绘图工具")

# 创建输入框和按钮
frame = tk.Frame(root)
frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)

tk.Label(frame, text="输入函数(使用 x 作为自变量):").pack(side=tk.LEFT, padx=5)
entry = tk.Entry(frame, width=30)
entry.pack(side=tk.LEFT, padx=5)
entry.insert(0, "x**2") # 默认函数

button = tk.Button(frame, text="绘制函数", command=plot_function)
button.pack(side=tk.LEFT, padx=5)

# 创建图像区域
fig, ax = plt.subplots(figsize=(5, 4), dpi=100)
ax.axhline(0, color="black", linewidth=0.5)
ax.axvline(0, color="black", linewidth=0.5)
ax.grid(True)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(fill=tk.BOTH, expand=1)

# 启动主循环
root.mainloop()

打包成 EXE

  1. 安装打包工具:

    1
    pip install pyinstaller
  2. 打包命令:
    在终端中执行以下命令,将脚本文件 plot_function.py 转换为 .exe

    1
    pyinstaller --onefile --noconsole plot_function.py
  3. 打包成功后,在 dist 文件夹中找到生成的 .exe 文件。


使用说明

  1. 打开软件。
  2. 在底部输入框中输入函数(如 x**2np.sin(x)),确保语法正确。
  3. 点击“绘制函数”按钮,图像会实时更新。