Search code examples
pythonpython-3.xtkintertkinter-entry

How can tkinter entry widget to "tab" automatically after certain digits/characters?


I am writing a python tkinter trying to have 2 entry widgets. After entering 5 digits in the first entry widget, I want the 6th digit could be jumped to next entry widget automatically. How can I rewrite it to make it come true?

import tkinter as tk

root=tk.Tk()
canvas1=tk.Canvas(root,width=400,height=400,bg='#FFFFFF')
canvas1.pack()

entry1=tk.Entry(root,width=8)
canvas1.create_window(10,100,window=entry1,anchor='nw')
entry1.focus_set()
  
entry1=tk.Entry(root,width=8)
canvas1.create_window(100,100,window=entry1,anchor='nw')

root.mainloop()

Solution

  • Entry validation is what you are looking for. Try the following code:

    import tkinter as tk
    
    
    def on_validate(P):
        if len(P) == 5:  # The 6th entry is taken up by the 2nd entry widget
            entry2.focus_set()
        return True
    
    root = tk.Tk()
    canvas1 = tk.Canvas(root, width=400, height=400, bg='#FFFFFF')
    canvas1.pack()
    
    entry1 = tk.Entry(root, width=8, validate="key")
    entry1['validatecommand'] = (entry1.register(on_validate), '%P')
    canvas1.create_window(10, 100, window=entry1, anchor='nw')
    entry1.focus_set()
    
    entry2 = tk.Entry(root, width=8)
    canvas1.create_window(100, 100, window=entry2, anchor='nw')
    
    root.mainloop()