user3396592
user3396592

Reputation: 373

Function being called even though Matplotlib button hasn't been clicked

I have a program which shows an image (fig 1). When the image is clicked it shows the colour in the image that was clicked in a separate Matplotlib window (fig 2). Fig 2 has some buttons that call different functions when they are clicked.

My problem is that the functions that are meant to be called in fig 2 are being called when fig 1 is clicked.

The code looks like this:

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"

So test() is called instantly when on_pixel_click() is called even though theoretically it should wait until the button is clicked because of the button.on_clicked() command.

Any help?

Thanks in advance :)

Upvotes: 0

Views: 198

Answers (1)

Pep_8_Guardiola
Pep_8_Guardiola

Reputation: 5252

On this line:

button.on_clicked(test())

You are telling Python to execute your test function, rather than just passing a reference to it. Remove the brackets and it should sort it:

button.on_clicked(test)

Upvotes: 1

Related Questions