1

Is it possible to bind all instances of ttk.Button in my app in a single bind to '<Return>' event, so when Enter button is pressed, ttk.Button callback will be triggered.

In addition, some buttons may have a lambda callback, so is there a generalised way to do that?

I know this can be done by explicitly binding every button, but can it be done with bind_class, perhaps? Or subclassing a ttk.Button?

Clarification: I don't want the same callback be triggered when any of the buttons are pressed with button. I want buttons own callback triggered, when this particular button is in focus and button is pressed on keyboard. And this is not a default behavior of a ttk.Button widget.

I am using Python 3.

zondo
  • 19,901
  • 8
  • 44
  • 83
Mikhail T.
  • 1,240
  • 12
  • 21
  • 1
    so that they get invoked? (Their `command` gets called) That should happen by default. Or do you mean you want to call a single callback when *any* button is selected when the user hits `` in which case yes you would use `bind_class`. – Tadhg McDonald-Jensen Jun 15 '16 at 15:18
  • Thanks for answering! I would like to make single bind statement. In the end, when some particular button is in focus and Return is pressed, I would like to get this specific focused Button to be invoked – Mikhail T. Jun 15 '16 at 15:24
  • 2
    Possible duplicate of [Tkinter - Same event for multiple buttons](http://stackoverflow.com/questions/35470943/tkinter-same-event-for-multiple-buttons) – Billal Begueradj Jun 15 '16 at 15:24
  • @BillalBEGUERADJ: No, the subject is different. I 've added clarification. – Mikhail T. Jun 15 '16 at 18:56

1 Answers1

2

You can manually invoke a button using their .invoke() method, since you are making a binding you will have access to the specific widget in question with e.widget and invoke that specific button:

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="button1",
                    command = lambda:print("hit button1"))
button1.grid()
button2 = tk.Button(root, text="button2",
                    command = lambda:print("hit button2"))
button2.grid()

def wrapper(e):
    print("<Return> was pressed on a button!")
    e.widget.invoke()
root.bind_class("Button","<Return>",wrapper)
root.mainloop()

Now if you press <Return> while one of the buttons have focus wrapper will be called and then invoke() the specific button that was in focus.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59