如何找到类似于How'matplotlib.pyplot.gcf()`works?

2024-06-26 09:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个pyqtgraph对应的matplotlib.pyplot.gcf()函数,它返回对当前图形的引用。我想要一个返回当前pyqtgraphGraphicsWindow实例的引用的函数。有办法吗?在


Tags: 实例函数图形matplotlibgcfpyqtgraphpyplot办法
2条回答

pyqtgraph中没有隐式的“当前图形”概念;每个窗口或图形对象都应该显式引用。例如:

plot_window = pg.plot()

# Add data to this plot:
plot_curve = plot_window.plot(data)

# Update data in this curve:
plot_curve.setData(data)

如果您只想获取当前活动窗口,那么Qt可以提供:http://doc.qt.io/qt-5/qapplication.html#activeWindow

这可以通过

  1. 创建跟踪窗口的全局列表
  2. 子类化pg.GraphicsWindow或{}(假设您import pyqtgraph as pg
  3. 将新创建的子类窗口/小部件实例添加到全局跟踪列表
  4. 重写closeEvent以便在窗口关闭时从跟踪器中删除窗口。在

这是因为the way python caches imported modules,所以再次导入{}应该访问同一个变量。在

例如:maketracking.py

import warnings


class WTracker:

    def __init__(self):
        self.open_windows = []

    def window_closed(self, win):
        if win in self.open_windows:
            self.open_windows.remove(win)
        else:
            warnings.warn('  tracker received notification of closing of untracked window!')

    def window_opened(self, win):
        self.open_windows += [win]


tracker = WTracker()

然后figure.py

^{pr2}$

最后,我们可以实现gcf();让我们把它放在pyplot.py中:

from tracking import tracker
from figure import Figure


def gcf():
    if len(tracker.open_windows):
        return tracker.open_windows[-1]
    else:
        return Figure()

然后用tester.py进行测试:

import sys
from PyQt4 import QtGui
from figure import Figure
from pyplot import gcf

app = QtGui.QApplication(sys.argv)

fig1 = gcf()
fig2 = gcf()
fig3 = Figure()
fig4 = gcf()
fig4.close()
fig5 = gcf()

print('fig2 is fig1 = {}'.format(fig2 is fig1))
print('fig3 is fig1 = {}'.format(fig3 is fig1))
print('fig4 is fig3 = {}'.format(fig4 is fig3))
print('fig5 is fig3 = {}'.format(fig5 is fig3))
print('fig5 is fig1 = {}'.format(fig5 is fig1))

结果是:

$ python tester.py
fig2 is fig1 = True
fig3 is fig1 = False
fig4 is fig3 = True
fig5 is fig3 = False
fig5 is fig1 = True

子类化pg.PlotWidget而不是pg.GraphicsWindow起作用,但随后必须创建一个布局,将其设置为中心项,然后运行self.show()。在

相关问题 更多 >