0

Is it possible to have arguments and an event listener on a function? I have two entries that I want to clear on <FocusIn>. I thought it would be simple and bind delete like self.minutes.bind("<FocusIn>", self.minutes.delete(0, "end)), but no that would be too easy. So I created a function to wipe any entry I want whenever focused. My function is simply:

def entry_clear(entry, e):
     entry.delete(0, "end")

This results in entry_clear() missing 1 required positional argument: 'e' but if I use it with self it works fine like:

def entry_clear(self, e):
     self.minutes.delete(0, "end")

But of course now I have to specify the exact entry I want in the function, rather than being used for any entry. Thanks for any help.

1
  • those functions are not that different, you'll need to show more of your code, if you ran the second function under the same circumstances as the first one, you should get the same error, also the passed events should have a widget attribute that you can use Commented Aug 4, 2022 at 20:20

1 Answer 1

2

You do not really need to pass the widget itself because tkinter passes an Event object implicitly with bind. This Event object has an attribute called widget which will be the widget that originally triggered the event. So you can just delete the items of that widget directly:

def entry_clear(self, e): # `e` is `Event` object
     e.widget.delete(0, "end")

Now to answer your original question:

Is it possible to have arguments and an event listener on a function?

Yes it is possible, but it depends on how you use bind, a fairly common way is like:

ent.bind('<1>', lambda event: callback(event, ent))

Instead of this, I would always use the first method.

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.