我希望每次用户点击该行时都会出现一个矩形。我已经在程序上像这个例子那样工作:http://www.daniweb.com/software-development/python/code/216648但是一旦我实现了iPython兼容性并开始使用类,我就不能再使用app.MainLoop()而不会导致程序崩溃。如何从类中刷新wx.Frame对象?为什么self.figure.canvas.draw()不起作用?
代码如下。使用-pylab选项打开ipython。 x = [ - 10,10]和y = x是这个问题的不错参数。
import wx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *
import IPython.ipapi
ip = IPython.ipapi.get()
import sys
class MainCanvas(wx.Frame):
""" Set up the canvas and plot on which the rectangle will lie """
def __init__(self, *args):
wx.Frame.__init__(self,None,-1, size=(550,350))
self.x = args[0]
self.y = args[1]
self.figure = plt.figure()
self.axes = self.figure.add_subplot(111)
self.axes.plot(*args)
self.line, = self.axes.plot(self.x, self.y, picker = 3,
visible = False)
self.canvas = FigCanv(self, -1, self.figure)
self.rect = patches.Rectangle((0, 0), 2, 2, visible=True)
self.axes.add_patch(self.rect)
self.figure.canvas.mpl_connect('pick_event', self.onPick)
def onPick(self, event):
""" Move rectangle to last click on line """
self.rect.set_x(event.mouseevent.xdata)
self.rect.set_y(event.mouseevent.ydata)
self.rect.set_visible(True)
print "rect x: ", self.rect.get_x()
print "rect y: ", self.rect.get_y()
self.figure.canvas.draw()
def run_this_plot(self, arg_s=''):
""" Run in iPython
Examples
In [1]: import demo
In [2]: runplot x y <z>
Where x, y, and z are numbers of any type
"""
args = []
for arg in arg_s.split():
try:
args.append(self.shell.user_ns[arg])
except KeyError:
raise ValueError("Invalid argument: %r" % arg)
mc = MainCanvas(*args)
ip.expose_magic("runplot", run_this_plot)
谢谢! --Erin
答案 0 :(得分:1)
似乎matplotlib设置为使用除wx之外的后端。尝试在matplotlibrc文件中设置它,或者可以在程序中设置它(但必须在导入matplotlib之前设置它)。说明为here。