1

Is it possible to run a function with both a button press and an event? When I try to run this function by pressing the button, it, understandably, gives an error

TypeError: listFiller() missing 1 required positional argument: 'event'.

Couldn't find a similar problem, but maybe that is just my lack of programming knowledge.

Code:

class MyClass:

    def __init__(self, master):
        self.myButton = tk.Button(master, text='ok', command=self.listFiller)
        self.myButton.pack()

        self.myEntry = tk.Entry(master)
        self.myEntry.bind("<Return>",self.listFiller)
        self.myEntry.pack()

    def listFiller(self, event):
        data = self.myEntry.get()
        print(data)
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46

1 Answers1

5

Try setting event=None for the function and then passing event from the bind only, like:

self.myButton = tk.Button(master, text='ok', command=self.listFiller)
.....

self.myEntry.bind("<Return>", lambda e: self.listFiller()) # Same as lambda e: self.listFiller(e)

def listFiller(self, event=None):
    data = self.myEntry.get()

This way, when you press the button, event is taken as None. But when bind is triggered(i.e.,Enter is hit), event is passed on implicitly(works even if you pass it explicitly) as e.

So after you have understood how this works behind the hood, now even if you remove lambda, e would still get passed as event as it happens implicitly.

self.myEntry.bind("<Return>",self.listFiller) # As mentioned by Lafexlos

Though keep in mind, when you press a tkinter button, you cannot use any attributes from event, like event.keysym or anything, but it would work if you use Enter key.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
  • 1
    I don't think you need lambda in the `bind`. you can directly use `self.myEntry.bind("", self.listFiller)` and that should pass `event` parameter automatically. – Lafexlos Apr 09 '21 at 09:05
  • @Lafexlos Yes, that is true too. I wanted to show the working behind it. Ill add that in. Thanks for mentioning it. – Delrius Euphoria Apr 09 '21 at 09:08