Bird
0
0

The following code is intended to print the mouse button pressed, but it raises an error:

medium📝 Debug Q14 of 15
Matplotlib - Interactive Features
The following code is intended to print the mouse button pressed, but it raises an error:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

def on_click(event):
    print(f"Button pressed: {event.button}")

fig.canvas.mpl_connect('button_press_event', on_click())
plt.show()

What is the error and how to fix it?
AThe function is called immediately; remove parentheses in mpl_connect
BThe event name is wrong; use 'mouse_press' instead
Cevent.button does not exist; use event.key instead
Dmpl_connect should be called on ax, not fig
Step-by-Step Solution
Solution:
  1. Step 1: Identify the error in function connection

    Using on_click() calls the function immediately instead of passing it as a reference.
  2. Step 2: Correct the function reference in mpl_connect

    Remove parentheses to pass the function itself: fig.canvas.mpl_connect('button_press_event', on_click).
  3. Final Answer:

    The function is called immediately; remove parentheses in mpl_connect -> Option A
  4. Quick Check:

    Pass function, not call it = D [OK]
Quick Trick: Pass function name without () to mpl_connect [OK]
Common Mistakes:
  • Calling the function instead of passing it
  • Using wrong event names
  • Trying to access wrong event attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Matplotlib Quizzes