我正在尝试使matplotlib与wxPython合作,下面列出的我的应用程序表现得很尴尬:在Ubuntu下它按预期工作,但在Windows XP下它似乎冻结,即按钮不响应点击,元素重叠(好像GridSizer不起作用)。我究竟做错了什么?
更新:将GridSizer更改为BoxSizer后,一切都在两个操作系统下运行, 但是GridSizer的问题仍未解决。
# wxPython module
import wx
# Matplotlib Figure object
from matplotlib.figure import Figure
# Numpy functions for image creation
import numpy as np
# import the WxAgg FigureCanvas object, that binds Figure to
# WxAgg backend. In this case, this is a wxPanel
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigureCanvas
class MyFigurePanel(wx.Panel):
"""Class to represent a Matplotlib Figure as a wxFrame"""
def __init__(self, parent):
wx.Panel.__init__(self, parent)
# usual Matplotlib functions
self.figure = Figure()#figsize=(6, 4), dpi=100)
self.axes = self.figure.add_subplot(111)
x = np.arange(0, 6, .01)
y = np.sin(x**2)*np.exp(-x)
self.axes.plot(x, y)
# initialize the FigureCanvas, mapping the figure to
# the Wx backend
self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
class MyButtonPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
save_button = wx.Button(self, label = 'SAVE se')
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None)
panelx = wx.Panel(self)
self.figure = MyFigurePanel(panelx)
self.buttons = MyButtonPanel(panelx)
grid = wx.GridSizer(1,2)
grid.Add(self.figure)
grid.Add(self.buttons)
panelx.SetSizer(grid)
# Create a wrapper wxWidgets application
app = wx.PySimpleApp()
# instantiate the Matplotlib wxFrame
frame = MyFrame()
# show it
frame.Show(True)
# start wxWidgets mainloop
app.MainLoop()
答案 0 :(得分:3)
这有效(修改MyFrame
后):
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigureCanvas
class MyFigurePanel(wx.Panel):
"""Class to represent a Matplotlib Figure as a wxFrame"""
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.figure = Figure()#figsize=(6, 4), dpi=100)
self.axes = self.figure.add_subplot(111)
x = np.arange(0, 6, .01)
y = np.sin(x**2)*np.exp(-x)
self.axes.plot(x, y)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
class MyButtonPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
button = wx.Button(self, label = 'SAVE se')
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.figure = MyFigurePanel(self)
self.buttons = MyButtonPanel(self)
grid = wx.BoxSizer(wx.VERTICAL)
grid.Add(self.buttons, flag=wx.EXPAND)
grid.Add(self.figure, flag=wx.EXPAND)
self.SetSizer(grid)
self.Fit()
# Create a wrapper wxWidgets application
app = wx.PySimpleApp()
# instantiate the Matplotlib wxFrame
frame = MyFrame()
# show it
frame.Show(True)
# start wxWidgets mainloop
app.MainLoop()
让它运行的关键变化是取消MyFrame
中的面板。实际上你已经添加了两个面板。
我还使用wx.BoxSizer()
来获得更好的外观(GridSizer
生成相同大小的单元格)