数学公式的可视化计算器
2025-03-07 本文已影响0人
Python_Camp
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton
from PyQt6.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 设置窗口标题和大小
self.setWindowTitle("Function Visualizer")
self.setGeometry(100, 100, 800, 600)
# 创建中心小部件和主布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
# 创建顶部输入区域
input_layout = QHBoxLayout()
# 标签和输入框:输入函数
self.function_label = QLabel("Enter function (e.g., 2*x + 1):")
input_layout.addWidget(self.function_label)
self.function_input = QLineEdit()
self.function_input.setPlaceholderText("e.g., 2*x + 1")
input_layout.addWidget(self.function_input)
# 标签和输入框:输入 x 范围
self.xrange_label = QLabel("X range (min, max):")
input_layout.addWidget(self.xrange_label)
self.xmin_input = QLineEdit()
self.xmin_input.setPlaceholderText("min, e.g., -10")
self.xmin_input.setFixedWidth(100)
input_layout.addWidget(self.xmin_input)
self.xmax_input = QLineEdit()
self.xmax_input.setPlaceholderText("max, e.g., 10")
self.xmax_input.setFixedWidth(100)
input_layout.addWidget(self.xmax_input)
main_layout.addLayout(input_layout)
# 创建按钮
self.plot_button = QPushButton("Plot Function")
self.plot_button.setStyleSheet("background-color: #4CAF50; color: white; padding: 10px;")
self.plot_button.clicked.connect(self.plot_function)
main_layout.addWidget(self.plot_button)
# 创建 Matplotlib 图表区域
self.figure, self.ax = plt.subplots(figsize=(8, 4))
self.canvas = FigureCanvas(self.figure)
main_layout.addWidget(self.canvas)
# 初始化图表
self.ax.grid(True, linestyle='--', alpha=0.7)
self.ax.set_xlabel("X")
self.ax.set_ylabel("Y")
self.ax.set_title("Function Visualization")
def plot_function(self):
"""绘制用户输入的函数"""
try:
# 获取用户输入的函数和 x 范围
function_str = self.function_input.text().strip()
xmin = float(self.xmin_input.text() or -10) # 默认 -10
xmax = float(self.xmax_input.text() or 10) # 默认 10
if not function_str:
self.ax.set_title("Please enter a function!")
self.canvas.draw()
return
# 创建 x 数据
x = np.linspace(xmin, xmax, 1000) # 生成 1000 个点
# 使用 eval 解析函数(将 x 替换为 numpy 数组)
# 注意:为了安全性,实际生产中应使用更安全的解析方法(如 sympy)
y = eval(function_str.replace('x', 'x'), {'x': x, 'np': np})
# 清空当前图表并重新绘制
self.ax.clear()
self.ax.plot(x, y, color='blue', label=f'y = {function_str}')
self.ax.grid(True, linestyle='--', alpha=0.7)
self.ax.set_xlabel("X")
self.ax.set_ylabel("Y")
self.ax.set_title("Function Visualization")
self.ax.legend()
# 刷新图表
self.canvas.draw()
except Exception as e:
# 显示错误信息
self.ax.clear()
self.ax.text(0.5, 0.5, f"Error: {str(e)}",
ha='center', va='center', color='red', fontsize=12)
self.ax.set_title("Invalid Function or Range")
self.ax.axis('off')
self.canvas.draw()
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()