Skip to main content
 首页 » 编程设计

python之为什么我不能在 iPython 中使用 app.MainLoop()

2025年05月04日23telwanggs

我希望每次用户单击该行时都会出现一个矩形。我已经让这个像这个例子中的程序一样工作: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) 

谢谢! --艾琳

请您参考如下方法:

似乎 matplotlib 被设置为使用 wx 以外的后端。尝试在 matplotlibrc 文件中设置它,或者它可以在程序中设置(但必须在导入 matplotlib 之前设置)。说明是here .