【问题标题】:Multiple wxpython tabs handling matplotlib events badly多个 wxpython 选项卡严重处理 matplotlib 事件
【发布时间】:2012-08-08 11:57:07
【问题描述】:

我非常努力地理解这一点,感觉如此接近! 我有一个循环,我在其中创建了一些 wxpanels 并将它们附加到笔记本选项卡上。每个选项卡都包含一个图。最初对绘图的事件调用没有通过正确的绘图面板,因此事件处理函数报告了错误绘图的位置。我想我会用字典来解决这个问题:

    self.plotdict ["plot" + str(plotcounter)] = wx.Panel(self, id=wx.ID_ANY)

然后我能够更改我的函数,使其传递 dict 键而不是 plot,无论如何我感觉更好。

    self.plotdict ["plot" + str(plotcounter)].canvas.mpl_connect('motion_notify_event', lambda event: self.cbUpdateCursor(event, ("plot" + str(plotcounter))))

然而,即使这个循环已经运行了很多次,并且我在选项卡中有很多绘图,循环中的这一行总是将相同的键发送到函数 self.cbUpdateCursor,就好像它只使用函数调用创建的最后一个选项卡/绘图。

        def cbUpdateCursor(self, event, plot):
    if event.inaxes:
        text = 'x = %5.4f, y = %5.4f' % (event.xdata, event.ydata)
        print text
        print plot
        print self.plotdict[plot]
        print id(self.plotdict [plot])
        self.plotdict [plot].cursor_pos.SetLabel(text)

这意味着该函数的打印(仅用于测试)显示相同的绘图参考,无论哪个选项卡以及鼠标事件发生在哪个绘图上。

  Print results for mouse over plot1
    x = -127.8006, y = 135.9350
    plot3
    <wx._windows.Panel; proxy of <Swig Object of type 'wxPanel *' at 0x2f63758> >
    52125616
  Print results for mouse over plot2
    x = -185.0618, y = 137.9096
    plot3
    <wx._windows.Panel; proxy of <Swig Object of type 'wxPanel *' at 0x2f63758> >
    52125616

为什么我的画布上的鼠标事件会调用与绘图 3 相关的函数,而不管我的鼠标在哪个绘图上? (在这种情况下,情节 3 是最后一个创建的)。

【问题讨论】:

  • 能否请您发布相关的self.Bind() 电话?
  • 我似乎没有进行与此事件句柄相关的绑定调用。

标签: python event-handling matplotlib wxpython


【解决方案1】:

我认为您的问题可能是因为您需要关闭您的动作通知事件函数。可以在here 找到一些关于闭包的非常好的答案。

可能是这样的:

for plot_count in plot_counts:
    def update_plot(event, plot_count=plot_count):
        self.cbUpdateCursor(event, 'plot%s' % plot_count)

    self.plotdict['plot%s' % plot_count].canvas.mpl_connect('motion_notify_event', update_plot)

但是,由于您没有提供SSCCE,因此我无法测试是否确实如此。

【讨论】:

  • 我的代码现在很乱;很抱歉你需要更多。我通过“获取”活动页面以一种方式解决了这个问题。 codepage = self.nb.GetPage(self.nb.GetSelection())
  • 好的。那么您无法测试我建议的更改的结果吗?
  • pelson,我想我也在做同样的事情。我只在循环之外定义我的函数一次。你的有什么原因吗?
  • 很难说,但这就是这个答案的重点:如果我的答案是正确的,那么是的,函数在循环内确实很重要。如果您还没有这样做,我强烈建议您阅读我链接到的关于闭包的问题 (stackoverflow.com/questions/233673/lexical-closures-in-python)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
相关资源
最近更新 更多