Search code examples
pythontkintertkinter-entrydata-entry

Focusing on next entry box after typing a number in current entry box


I'm trying to see if there's a way to type a number between 1 and 4 into an entry box, then go to the next entry box (with the number entered into the box; the code below skips to the next entry without entering anything)

I'm creating a program that will take item-level data entry to be computed into different subscales. I have that part working in different code, but would prefer not to have to hit tab in between each text entry box since there will be a lot of them.

Basic code:

from tkinter import *

master = Tk()
root_menu = Menu(master)
master.config(menu = root_menu)

def nextentrybox(event):
    event.widget.tk_focusNext().focus()
    return('break')

Label(master, text='Q1',font=("Arial",8)).grid(row=0,column=0,sticky=E)
Q1=Entry(master, textvariable=StringVar)
Q1.grid(row=0,column=1)
Q1.bind('1',nextentrybox)
Q1.bind('2',nextentrybox)
Q1.bind('3',nextentrybox)
Q1.bind('4',nextentrybox)
Label(master, text='Q2',font=("Arial",8)).grid(row=1,column=0,sticky=E)
Q2=Entry(master, textvariable=StringVar)
Q2.grid(row=1,column=1)
Q2.bind('1',nextentrybox)
Q2.bind('2',nextentrybox)
Q2.bind('3',nextentrybox)
Q2.bind('4',nextentrybox)
### etc for rest of questions

### Scale sums, t-score lookups, and report generator to go here

file_menu = Menu(root_menu)
root_menu.add_cascade(label = "File", menu = file_menu)
file_menu.add_separator()
file_menu.add_command(label = "Quit", command = master.destroy)

mainloop()

Thanks for any help or pointers!


Solution

  • The simplest solution is to enter the event keysym before proceeding to the next field.

    In the following example, notice how I added a call to event.widget.insert before moving the focus:

    def nextentrybox(event):
        event.widget.insert("end", event.keysym)
        event.widget.tk_focusNext().focus()
        return('break')