我無法找到一個滿意的答案,所以我寫延伸matplotlib.figure.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()
將該文件作爲開頭文件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
工程!我從來沒有觸及過GUI編程,也不知道這是否會有任何副作用。如果你認爲應該這樣做,應該自由評論。
目前尚不清楚問題出在哪裏。你指的是以前的情節? – ebarr
@ebarr我的意思是,如何在關閉GUI窗口後再次查看圖形?再次創建一個'figure'和'plot'?我認爲應該有更好的方式來做到這一點。 –
因此'show'只能在腳本中運行一次,因爲它啓動Tk mainloop運行。該文檔稱「v1.0.0中的新增功能:show now現在只有在它尚未運行時纔會啓動GUI主循環,因此現在允許多個顯示調用。」你能否添加一些關於你需要什麼功能的信息?你在建立一個圖形用戶界面嗎?或者你只是想一個接一個地看看情節? – ebarr