重新打开 GTK 和 matplotlib 窗口 - GTK 窗口为空白



我的程序(使用glade GTK开发)接收一些数据,并可以选择显示一个单独的窗口,其中包含表示数据的matplotlib scatterplot

我的问题是,如果用户关闭图形window并重新打开它,则不会显示任何图形。这只是一个空白GTK Window.我确定有一个简单的解决方法,但是与我的问题(或GTKmatlplotlib集成)相关的可用资源并不多。

我已经为我的scatterplot创建了一个Module,因此我可以轻松地重用它。我只是想让它工作,所以代码的结构并不完美。

##Scatterplot Module:
import gtk
import matplotlib
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
from matplotlib.figure import Figure

class ScatterPlot:
    def __init__(self):
       self.window = gtk.Window()
       self.window.connect("destroy", lambda x: self.destroy())
       self.window.set_default_size(500,400)
       self.is_hidden = False
       self.figure = Figure(figsize = (5,4), dpi=100)
       self.ax = self.figure
       self.ax = self.ax.add_subplot(111)
       self.canvas = FigureCanvas(self.figure)
       self.window.add(self.canvas)
       self.Xs = list()
       self.Ys = list()
   def set_axis(self, xLimit = (0,384) , yLimit = (0,100)):
       self.ax.set_xlim(xLimit)
       self.ax.set_ylim(yLimit)
   def plot(self, xs, ys):
       self.Xs.extend([xs])
       self.Ys.extend([ys])
       self.ax.plot(xs,ys,'bo')
   def update(self):
       self.window.add(self.canvas)
   def set_title(self, title):
       self.ax.set_title(title)
   def show(self):
       self.window.show_all()
       self.is_hidden = False
   def hide(self):
       self.window.hide()
       self.is_hidden = True
   def destroy(self):
       self.window.destroy()

我像这样调用该模块:

class GUI:
    def __init__(self):
        self.scatterplot = scatterplot.ScatterPlot()
        #When the user presses the "Graph" button it calls the following function
    def graph():
        self.scatterplot.plot(someDataX, someDataY)
        self.scatterplot.set_axis()
        self.scatterplot.set_title("Some Title")
        self.scatterplot.show()

(这只是我的代码的一个例子。

scatterplot关闭时,我打电话给self.window.destroy而不是self.window.hide。尝试重新打开时,我调用相同的graph()函数,但如上所述,GTK Window不显示图形。(当我第一次打开它时,它完美显示)

我的猜测:

  • 我应该打电话给.hide()而不是.destroy()吗?
  • scatterplot 的构造函数中是否有一段代码需要再次调用才能创建plot
  • 还是每次调用graph()时都重新实例化plot

我的解决方案:

从:

class ScatterPlot:
    def __init__(self):
        #remove the following two lines
        self.canvas = FigureCanvas(self.figure)
        self.window.add(self.canvas)

将两行代码移动到show()

def show(self):
    self.canvas = FigureCanvas(self.figure)
    self.window.add(self.canvas)
    self.window.show_all()
    self.is_hidden = False

移动这两行代码可以在重新打开窗口时显示图形。

旁注:关闭窗口时同时调用.destroy().show()将起作用。不过,我不确定哪个更好。

最新更新