Home > Software engineering >  Python: Add optional argument into matplotlib button on_clicked function
Python: Add optional argument into matplotlib button on_clicked function

Time:11-21

I made some function of that kind:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def clicked(event):
    print("Button pressed")

button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(clicked)
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
plt.show()

My aim now, is to add an second argument into the clicked function. The function now has the following form:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def clicked(event, text):
    print("Button pressed" text)


button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(clicked(text=" its the first"))
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
b2.on_clicked(clicked(text=" its the second"))
plt.show()

But with that change I get the following error message:

Traceback (most recent call last):
  File "/bla/main.py", line 24, in <module>
    b1.on_clicked(clicked(text=" its the first"))
TypeError: clicked() missing 1 required positional argument: 'event'

Is their a way to put an second argument in such a function or is it required in Python to make two on_clicked functions in that case?

CodePudding user response:

the problem with your second code is that you are calling the function clicked when you use it inside b1.on_clicked. This raises the error.

Instead b1.on_clicked takes a function as an argument and then under the hood it calls that function, passing the event as a parameter.

you can do it like this

def fn_maker(text=''):
    def clicked(event):
        print(f"Button pressed{text}")
    return clicked

button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(fn_maker(text=" its the first"))
...
  • Related