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.
CodePudding user response:
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.