Python:在用户输入后动态更新绘图

时间:2014-11-25 03:58:08

标签: python numpy matplotlib pyqt

我正在制作一个可以评估和绘制简单函数的pyqt gui。用户输入函数和一系列x值。按下输出字段上的回车键后,gui应该用答案和生成的数据图更新输出字段。我无法弄清楚如何使用用户输入数据更新图表

#!/usr/bin/python2.7
import sys
import numpy as np
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        """ MENU BAR SETUP """

        """ FILE MENU """
        self.menuFile = self.menuBar().addMenu("&File")
        self.actionSaveAs = QAction("&Save As", self)
        self.connect(self.actionSaveAs, SIGNAL("triggered()"), self.saveas) 
        self.actionExit= QAction("&Exit", self)
        self.connect(self.actionExit, SIGNAL("triggered()"), self.close)   
        self.menuFile.addActions([self.actionSaveAs, self.actionExit])

        """ HELP MENU """
        self.menuHelp = self.menuBar().addMenu("&Help")
        self.actionAbout = QAction("&About", self)
        self.connect(self.actionAbout, SIGNAL("triggered()"), self.about)
        self.menuHelp.addActions([self.actionAbout])

        """ CENTRAL WIDGET """ 
        self.form = Form()
        self.setCentralWidget(self.form)

    def saveas(self) :
        fname = unicode(QFileDialog.getSaveFileName(self, "Save as..."))
        """ Do something with data """

    def about(self) :
        QMessageBox.about(self, "About Function Evaluator",
                          "This is my help message.")
class Form(QDialog) :
    def __init__(self, parent=None) :
        super(Form, self).__init__(parent)
        self.plot = MatplotlibCanvas()
        function_list = ["np.sin(x)", "np.cos(x)", "pow(x,2)"]
        self.function_edit = QComboBox(parent=None)
        self.function_edit.setEditable(True)
        self.function_edit.addItems(function_list)
        self.parameter_edit = QLineEdit("[1,3,1]")
        self.parameter_edit.selectAll()
        self.output_edit = QLineEdit("output = ...")
        self.output_edit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.plot)
        layout.addWidget(self.function_edit)
        layout.addWidget(self.parameter_edit)
        layout.addWidget(self.output_edit)
        self.setLayout(layout)
        self.function_edit.setFocus()
        self.connect(self.output_edit, SIGNAL("returnPressed()"),self.updateUI)
        self.setWindowTitle("Function Evaluator")

    def updateUI(self) :

        try :
            x = np.array(eval(str(self.parameter_edit.text())))
            f = eval(str(self.function_edit.currentText()))
            f_s = str(f).replace("[","").replace("]","")#.replace(" ", ", ").lstrip(', ')
            self.output_edit.setText(f_s)

        except :
            self.output_edit.setText("I can't code")


class MatplotlibCanvas(FigureCanvas) :
    """ This is borrowed heavily from the matplotlib documentation;
        specifically, see:
        http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html
    """
    def __init__(self, parent=None, width=5, height=4, dpi=100) :
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        self.axes.hold(False)
        self.compute_initial_figure()
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        t = np.arange(0.0, 3.0, 0.01)
        f = np.sin(2*np.pi*t)
        self.axes.plot(t, f)
        self.axes.set_xlabel('t')
        self.axes.set_ylabel('f(t)')     

app = QApplication(sys.argv)
main = MainWindow()
main.show()
app.exec_()

由于

1 个答案:

答案 0 :(得分:0)

您必须在updateUIslot中更新您的情节。

def updateUI(self):
    try :
        x = eval(str(self.parameter_edit.text()))
        f = eval(str(self.function_edit.currentText()))
        self.plot.update_figure(x, f)
        self.output_edit.clear()
    except Exception as e:
        self.output_edit.setText(str(e))

update_figure方法可能如下所示(您必须调用draw来显式触发重绘):

def update_figure(self, t, f):
    self.axes.plot(t, f)
    self.axes.set_xlabel('t')
    self.axes.set_ylabel('f(t)')
    self.draw()

请注意,evaldangerous,因为它允许在您的计划中执行任何代码(尝试在sys.exit()中输入parameter_edit ...)