使用matplotlib时:
from matplotlib import pyplot as plt
figure = plt.figure()
ax = figure.add_subplot(111)
ax.plot(x,y)
figure.show() # figure is shown in GUI
# How can I view the figure again after I closed the GUI window?
figure.show() # Exception in Tkinter callback... TclError: this isn't a Tk application
figure.show() # nothing happened
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
如果调用了Figure.show(),如何获取上一个图?
figure.add_suplot(111)如果我有多个数字,因此from pylab import *; plot(..); show()似乎不是我正在寻找的解决方案,是否有更方便的替代方法。
我渴望的是
showfunc(stuff) # or
stuff.showfunc()
Run Code Online (Sandbox Code Playgroud)
其中stuff是一个对象,其中包含布置在一张图片中的所有图,并且showfunc是无状态的(我是说,每次调用它时,我的行为就像第一次调用一样)。与之合作时可能matplotlib吗?
我找不到满意的答案,因此我通过编写一个自定义Figure类扩展matplotlib.figure.Figure并提供一个新show()方法来处理这个问题,该方法gtk.Window每次调用时都会创建一个对象。
import gtk
import sys
import os
import threading
from matplotlib.figure import Figure as MPLFigure
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NaviToolbar
class ThreadFigure(threading.Thread):
def __init__(self, figure, count):
threading.Thread.__init__(self)
self.figure = figure
self.count = count
def run(self):
window = gtk.Window()
# window.connect('destroy', gtk.main_quit)
window.set_default_size(640, 480)
window.set_icon_from_file(...) # provide an icon if you care about the looks
window.set_title('MPL Figure #{}'.format(self.count))
window.set_wmclass('MPL Figure', 'MPL Figure')
vbox = gtk.VBox()
window.add(vbox)
canvas = FigureCanvas(self.figure)
vbox.pack_start(canvas)
toolbar = NaviToolbar(canvas, window)
vbox.pack_start(toolbar, expand = False, fill = False)
window.show_all()
# gtk.main() ... should not be called, otherwise BLOCKING
class Figure(MPLFigure):
display_count = 0
def show(self):
Figure.display_count += 1
thrfig = ThreadFigure(self, Figure.display_count)
thrfig.start()
Run Code Online (Sandbox Code Playgroud)
使该文件作为IPython. 和
figure = Figure()
ax = figure.add_subplot(211)
... (same story as using standard `matplotlib.pyplot` )
figure.show()
# window closed accidentally or intentionally...
figure.show()
# as if `.show()` is never called
Run Code Online (Sandbox Code Playgroud)
作品!我从来没有接触过GUI编程,也不知道这是否会有任何副作用。如果您认为应该这样做,请自由发表评论。