0

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?

1

1 Answer 1

1

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"))
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.