Search code examples
python-3.xtkinterfocustkinter-entry

tkinter auto switch focus after write in entry


I have got 4 entry fields and I want to switch focus to next field after write one letter. So basically i want to write 4 letters, each one in another field, without touching mouse or Tab button.

from tkinter import *

root = Tk()
r1= StringVar()
r2= StringVar()
r3= StringVar()
r4= StringVar()

e1=Entry(root, textvariable=r1)
e1.pack()

e2=Entry(root, textvariable=r2)
e2.pack()

e3=Entry(root, textvariable=r3)
e3.pack()

e4=Entry(root, textvariable=r4)
e4.pack()

list=[e1,e2,e3,e4]
for i, element in enumerate(list):
    lista=[r1,r2,r3,r4]
    element.focus()
    while lista[i].get() == "":
        pass

root.mainloop()

How can I do that? Thanks for help :D


Solution

  • Your original code hangs before reaching root.mainloop() because the Entry() fields will never be edited. You have to use Tk events, e.g. after packing the Entry fields, you could try this:

    liste=[e1,e2,e3,e4]
    e1.focus()
    curre=0
    def nexte(e):
        global curre
        curre+=1
        if (curre<4):
            liste[curre].focus()
        else:
            root.unbind("<Key>")
            # we've got input into the last field, now do sth useful here...
    
    root.bind("<Key>",nexte)
    
    root.mainloop()