Reputation: 33
I've read so many other answers to such questions, but they don't work...So please don't mark it duplicate... I'm a Python self-learner, running on Windows on in Python 3.6. This is the code-
self.btnCalc = Button(self, text = "Calculate", command=self.calculate, bd=10)
self.btnCalc.grid(row = 11, column = 5)
self.btnCalc.bind('<Return>', self.calculate)
This is the link to the whole code (to calculate school grades).
Upvotes: 2
Views: 698
Reputation: 13347
I think you want to trigger the command without clicking the button, so you need to bind the event to your main widget, self
.
You don't bind the event to the button command, but to the command directly. When you create a binding on a parent, it's available to all children widgets, Entry...
you can use this :
self.bind('<Return>', self.calculate)
# or self.bind('<KP_Enter>', self.calculate) to trigger numpad Return
But your method calculate
must have a parameter for event, even if you don't use it :
def calculate(self, event=None):
Explanation about event :
When you bind a function to an event with the method widget.bind(...)
, tkinter calls the function with one parameter : the event. It contains informations about the action triggered, like the coordinates of mouse, or any relevant detail to handle the event correctly.
You don't use it in your function (yet ?), but you need to declare it.
Then, as you are using the function from the button AND from the binding, it has to be declared as an optional parameter, with a default value : None
, because the command inside a button doesn't generate this event
parameter when it calls the function.
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
Upvotes: 2