即使尚未单击Matplotlib按钮,仍调用函数



我有一个显示图像的程序(图1)。单击图像时,它会显示在单独的 Matplotlib 窗口中单击的图像中的颜色(图 2)。图 2 有一些按钮在单击时调用不同的函数。

我的问题是,当单击图 1 时,应该在图 2 中调用的函数被调用。

代码如下所示:

def show_fig1(img):
  # Plot the image
  plt.figure(1)
  ax = plt.gca()
  fig = plt.gcf()
  implot = ax.imshow(img)
  # Detect a click on the image
  cid = fig.canvas.mpl_connect('button_press_event', on_pixel_click)
  plt.show(block=True)
# Called when fig1 is clicked
def on_pixel_click(event):
  if event.xdata != None and event.ydata != None:
    # Do some computation here that gets the image for fig2
    img = get_fig2_img()    
    show_fig2(img, event)

def show_fig2(img, event):
  plt.figure(2)
  plt.imshow(img)
  # Specify coordinates of the button
  ax = plt.axes([0.0, 0.0, 0.2, 0.1])
  # Add the button
  button = Button(ax, 'button')
  # Detect a click on the button
  button.on_clicked(test())
  plt.show(block=True)

def test():
  print "Button clicked"

因此,当调用 on_pixel_click() 时会立即调用 test(),即使理论上它应该等到 button.on_clicked() 命令而单击按钮。

有什么帮助吗?

提前致谢:)

在这一行:

button.on_clicked(test())

你告诉 Python 执行你的test函数,而不仅仅是传递对它的引用。删除括号,它应该对其进行排序:

button.on_clicked(test)

最新更新