【问题标题】:Function being called even though Matplotlib button hasn't been clicked即使尚未单击 ​​Matplotlib 按钮,也会调用函数
【发布时间】:2016-03-17 10:37:11
【问题描述】:

我有一个显示图像的程序(图 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() 命令。

有什么帮助吗?

提前致谢:)

【问题讨论】:

    标签: python button matplotlib widget


    【解决方案1】:

    在这一行:

    button.on_clicked(test())
    

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

    button.on_clicked(test)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-22
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多