简体   繁体   中英

Tkinter Initial Cursor position and Enter to press button

I am making a box that is similar to the tkMessageBox. There are two simple behaviors that I want to the box to have. First I want the button to be selected automatically when the window opens, and second I want to be able to press enter to push the button. Sounds simple and I realize that I could use the tkinterMessageBox to do this same thing, but this is a stepping stone, and I would like to know how to do this in the future for other things.

The current behavior of the window below is that it opens, and if I press tab it will select the button, but then i can only press the button with the mouse. Again the desired functionality is to have the button selected right away and be able to press the button with the enter key.

import Tkinter, tkMessageBox
from Tkinter import *

def closewindow():
    Messagebox.destroy()

Messagebox=Tk()
l3=Label( Messagebox, text="This is your preview!  Align camera then press ESC")
b3=Button(Messagebox, text="Okay", command=closewindow)
l3.grid(row=1,column=1)
b3.grid(row=2,column=1)

Messagebox.mainloop()

You can actually do this with just two lines of code:

b3.bind('<Return>', lambda _: closewindow())
b3.focus_set()

The first binds the button to the Enter key and the second sets the application's focus on the button.

Note that I had to use a lambda with the binding to handle the event object that will be sent to the callback. You could however change the definition of closewindow to handle this:

def closewindow(event=None):
    Messagebox.destroy()

Now you can just do:

b3.bind('<Return>', closewindow)

For more information on bindings in Tkinter, see Events and Bindings over on Effbot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM