tkinter default button in a widget
Asked Answered
S

3

9

this seemed easy...

I wrote a dialog widget where I put some entries, buttons etc - among which a button I'd like to activate by mouse click, but also by pressing return. I read time ago that it was just necessary to set its default option, but I think that it changed in recent versions.

Do you know how it is possible to set it ?

thanks!

Serbocroatian answered 21/5, 2012 at 14:37 Comment(1)
The default config option for a button is just a visual, you don't need to set it, but if you're going to make it act like the default you should. (And bind <Return> to invoke it as Steven Rumbalski indicated.)Brede
G
10

Bind a callback to the '<Return>' event to the window (often called root in Tkinter) or to the containing frame. Have the callback accept an event parameter (which you can ignore) and have it invoke() your button's callback.

root.bind('<Return>', (lambda e, b=b: b.invoke())) # b is your button
Graecize answered 21/5, 2012 at 14:50 Comment(1)
it would have been cleaner as an option to the selected button, but I can live with this: it works, thank you!Serbocroatian
B
2
def myaction():
    print('Your action in action')

def myquit():
    root.destroy()

root = Tk()
label = Label(root, text='Label Text').pack(expand=YES, fill=BOTH)
label.bind('<Return>', myaction)
label.bind('<Key-Escape>', myquit)
ok = Button(label, text='My Action', command=myaction).pack(side=LEFT)
quit_but = Button(label, text='QUIT', command=myquit).pack(side=RIGHT)
root.mainloop()
  1. You must declare your functions first.
  2. Notice that the 'My Action' button and the Return key both call myaction and 'QUIT', and the Esc key both call myquit.

Hope that helps.

Ballesteros answered 12/10, 2019 at 4:45 Comment(0)
A
-1

If your tkinter window was constructed within a class you'd only need to bind the <Return> to the command of the button rather than to both:

self.bind('<Return>', self.btncommand)

where self refers to your window or frame. When Enter is pressed btncommand function is run by default.

Achene answered 12/5 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.