Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Add optional argument into matplotlib button on_clicked function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"))
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading