我非常努力地理解这一点,感觉非常接近! 我有一个循环,我在其中创建一些wxpanels并将它们附加到笔记本标签。每个选项卡都包含一个图。最初在绘图上的事件调用未通过正确的绘图面板,因此事件处理函数报告了错误绘图的位置。我以为我会用dict来解决这个问题:
self.plotdict ["plot" + str(plotcounter)] = wx.Panel(self, id=wx.ID_ANY)
然后我能够改变我的功能,所以它传递了dict键而不是情节,无论如何我感觉更好。
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是最后一个创建的)。
答案 0 :(得分: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我无法测试实际情况。