Limiting entry on a tk widget Limiting entry on a tk widget tkinter tkinter

Limiting entry on a tk widget


Ok I did try with the trace variable, on a short piece of test code , this is excactly what I was searching for !! I like the fact you can prototype so easily in Python ;)

def main():    passif __name__ == '__main__':    main()from Tkinter import *def callback(sv):    c = sv.get()[0:9]    print "c=" , c    sv.set(c)root = Tk()sv = StringVar()sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))e = Entry(root, textvariable=sv)e.pack()root.mainloop()


I know its too late to add any answers to this, just found a simpler way to represent what Wabara had answered. This will help if you need multiple entry limits and each to a user-defined length limit. Here's a code working on Python 3.6.5:

def main():    passif __name__ == '__main__':    main()from tkinter import *def limit_entry(str_var,length):    def callback(str_var):        c = str_var.get()[0:length]        str_var.set(c)    str_var.trace("w", lambda name, index, mode, str_var=str_var: callback(str_var))root = Tk()abc = StringVar()xyz = StringVar()limit_entry(abc,3)limit_entry(xyz,5)e1 = Entry(root, textvariable=abc)e2 = Entry(root, textvariable=xyz)e1.pack()e2.pack()root.mainloop()


The simplest solution is to put a trace on the variable. When the trace fires, check the length of the value and then delete any characters that exceed the limit.

If you don't like that solution, Tkinter also has built-in facilities to do input validation on entry widgets. This is a somewhat under-documented feature of Tkinter. For an example, see my answer to the question Python/Tkinter: Interactively validating Entry widget content