Anton Davidouski
Anton Davidouski

Reputation: 9

How can I bind the enter key to a command while having a button do the same thing?

I have a function whiten class. There is also a button which activates the function. I also want to make it so the user can press the enter key and it would run the function.

my current code looks something like this (simplified)

myButton = Button(text = "My Button", command = self.myFunction)
root.bind('<Return>', self.myFunction2)

def myFunction(self):
   pass

def myFunction(self, event):
   pass

I am using 2 functions because another answer on here said that it would work if I added another argument to one of the function (called event in this case)

This code works but I want to find a more efficient way to do this as each function is quite long and it is a hassle to change both of them when Im making a change.

if I try bind the enter key to myFunction(self), I get an error saying that 2 positional retirements wee given.

Upvotes: 0

Views: 52

Answers (1)

fhdrsdg
fhdrsdg

Reputation: 10532

Define your function as

def myFunction(self, event=None):

This will accept being called with or without the event argument. None is used as the default value for event when it isn't passed.

Upvotes: 2

Related Questions