开发者

Why can't I use app.MainLoop() with iPython?

开发者 https://www.devze.com 2023-04-03 03:04 出处:网络
I\'d like a rectangle to appear every time the user clicks on the line. I\'ve gotten this to work procedurally like in this example: http://www.daniweb.com/software-development/python/code/216648 but

I'd like a rectangle to appear every time the user clicks on the line. I've gotten this to work procedurally like in this example: http://www.daniweb.com/software-development/python/code/216648 but once I implemented iPython compatibility and started using classes, I could no longer use the app.MainLoop() without the program crashing. How do I refresh a wx.Frame object from inside a class? Why does the self.figure.canvas.draw() not work?

The code is below. Open ipython with the -pylab option. x = [-10,10] and y = x are decent parameters for this problem.

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
    """
   开发者_StackOverflow社区 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)

Thanks! --Erin


It seems likely that matplotlib is set to use a backend other than wx. Try either setting this in the matplotlibrc file, or it can be set in the program (but it must be set before matplotlib is imported). Instructions are here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号