Search code examples
pythonvalidationeventstkinterbind

How to generate tab key even when enter key pressed in TKinter (python)?


I'm trying to find out how to generate a TAB key event in tkinter/python.

I have a key binding in tkinter that works for the return key.

am_field_txt.bind('<Return>', next_focus)

Instead of calling the function (next_focus), I just want to generate a TAB event, so that instead the existing validation for the entry being used will be able to run using 'focusout' that happens when a Tab key is pressed. (I have setup the text entry with validation so that on the validate=focusout it does the checks and handles everything; but I'd like it to handle the one case where the user could press return instead of a 'focusout' condition (tab or clicking out of the text box)). I don't really want to use validate=key because then that routine is run any time a key is pressed (plus it already is setup and working for focusout).

Is there a simple way to bind the return key for an entry, so that instead a TAB event happens?

I found documentation on the web for TCL that says this:

bind .w <Return> {focus [tk_focusNext %W]}
bind .w <Return> {event generate %W <Tab>}

For the last line is what I'd like to do - except in a format/syntax for Python & tkinter. I've used the tk_focusNext function but again its a different syntax for tkinter/python so I think from the second line it must mean there is a way to just generate a TAB key if a RETURN key is pressed. (Side not, tk_focusNext doesn't really work right either, seems to chose a different focus than the tab key does... but that's a different topic).


Solution

  • You can use TCL code as argument in Python bind

    import tkinter as tk
    
    root = tk.Tk()
    
    e1 = tk.Entry(root)
    e1.pack()
    e2 = tk.Entry(root)
    e2.pack()
    
    #bind .w <Return> {event generate %W <Tab>}
    e1.bind('<Return>', 'event generate %W <Tab>')
    e2.bind('<Return>', 'event generate %W <Tab>')
    
    root.mainloop()
    

    There is also event_generate()

    e2.bind('<Return>', lambda x:root.event_generate('<Tab>'))