【发布时间】:2019-11-09 23:50:44
【问题描述】:
我正在尝试使用嵌入在 QT 小部件中的 matplotlibs 更新几个绘图。现在我可以在窗口中更新一个情节。但是,当我尝试通过单击按钮切换到另一个绘图时,程序会冻结。
这是我用来了解如何使用编程工具集成到更大程序中的测试脚本。我修改了这个问题的代码:How to embed matplotlib in pyqt - for Dummies
我已经被这个问题困扰了一段时间了。我知道我错过了一些非常简单的东西。
import random
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure1 = Figure()
self.figure2 = Figure()
self.current = "fig1"
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure1)
self.ax1 = self.figure1.add_subplot(111)
self.ax2 = self.figure2.add_subplot(111)
self.line1, = self.ax1.plot([], [], 'r', lw=2)
self.line2, = self.ax2.plot([], [], 'b', lw=2)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
self.update()
def update(self):
datax = [random.random() for i in range(10)]
datay = [random.random() for i in range(10)]
self.line1.set_xdata(datax)
self.line1.set_ydata(datay)
self.ax1.relim()
self.ax1.autoscale_view()
self.line2.set_xdata(datax)
self.line2.set_ydata(datay)
self.ax2.relim()
self.ax2.autoscale_view()
self.canvas.draw()
QtCore.QTimer.singleShot(1, self.update)
def plot(self):
if self.current == "fig1":
self.canvas = FigureCanvas(self.figure2)
self.current = "fig2"
elif self.current == "fig2":
self.canvas = FigureCanvas(self.figure1)
self.current = "fig1"
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
当我单击此按钮时,它应该开始绘制另一个图。我没有收到任何错误消息。
【问题讨论】:
-
另一个情节是什么意思?其他情节会在哪里显示?
-
我想要一个显示 matplotlib 图的窗口,当我单击按钮时,我想让图切换到另一个 matplot 图。因此,窗口中一次只显示我的两个绘图中的一个,我可以通过点击按钮在两者之间切换。
标签: python matplotlib pyqt pyqt4