我试图实现一个槽方法,它将清除作为QtWidget一部分的matplotlib图形。我在Windows 7和10上尝试过使用Python 3.6和3.5,我也有同样的行为。
我的问题是,当从主代码块或绘制图形的类中调用擦除方法时,我可以完全清除图形。但是,每当这个相同的方法被称为PyQT信号的槽时,槽实际上被激活,但是对fig.clf()的调用并没有清除该图。
以下代码显示了问题:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication,QMainWindow, QSizePolicy,QWidget,QVBoxLayout, QPushButton
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class GraphPopulate(FigureCanvas):
def __init__(self, parent=None):
self.fig = Figure(figsize=(6,4))
self.ax = self.fig.add_axes([0.07, 0.16, 0.95, 0.95]) # fraction of figure size #
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
x = [2000, 2001, 2002, 2003, 2004]
y = [10, 20, 30, 40, 50]
self.plt = self.ax.plot(x, y)
# self.wipe() # OK This one works as well
# self.plt.close(self.fig) # close the app, does not only clear figure
def wipe(self):
print('wipe start')
# del self.fig # close the app on second call, does not only clear figure !!
# self.plt.close(fig) # close the app, does not only clear figure
rc = self.fig.clf()
print('return code from clf() '+ str(rc))
print('wipe stop')
if __name__ == '__main__':
# create main window
app = QApplication(sys.argv)
MainWindow = QMainWindow()
MainWindow.resize(800, 600)
# create widget to be used by MathPlotlib
WidgetMatplot = QWidget(MainWindow)
WidgetMatplot.setGeometry(QRect(10, 40, 500, 500))
# create Push Button with clicked signal linked to GraphPopulate.wipe() slot
button = QPushButton(MainWindow)
button.setText("Push Me !")
# add widget to vertical box layout
hbox = QVBoxLayout(MainWindow)
hbox.addWidget(WidgetMatplot)
hbox.addWidget(button)
g = GraphPopulate(WidgetMatplot)
button.pyqtConfigure(clicked=g.wipe) # NOT OK !!!!!!! g.wipe is triggered as prints statements show
# on console but self.fig.clf() has no effect
MainWindow.show()
# g.wipe() # OK
sys.exit(app.exec_())
我已经发表评论,如果取消评论实际上是清除数字或关闭整个应用程序。
看起来像" matplotlib上下文"从signa-slot连接调用时与从其他调用调用时不同。
可能是我想念一些微不足道的事情。如果对此抱歉,但我无法找到自己调查的任何方向......所以我依靠你们发现它们。
谢谢 - Thibault
答案 0 :(得分:0)
在您的代码中,图形已成功清除。你只是没有看到它,因为没有人告诉这个数字它需要重新绘制。
如果你重新绘制图形,你会发现它确实是空的。
def wipe(self):
self.fig.clf()
self.fig.canvas.draw_idle()