Limiting entry on a tk widget
Solution 1
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():
pass
if __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()
Solution 2
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():
pass
if __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()
Solution 3
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
Waraba
Updated on June 04, 2022Comments
-
Waraba almost 2 years
I have trouble finding a way to limit the entry length of entry widgets, I would like to limit it to 20 characters, i.e. when I click on a sequence or the other I would like to be able to edit it but stay in the 20 characters limit. In or order to keep the code light , should I use a regex , a loop or check the entry with an event ?
Here is my code:
import Tkinter from Tkinter import * import tkFileDialog root = Tkinter.Tk() edit1 =StringVar() edit2 =StringVar() s = StringVar() s = "GATACACGCGCGCGTATATATTACGCGCGCGATACA" lb01=Label(root,text="sequence1") lb01v=Entry(root,textvariable=edit1,width=20) lb01v.delete(0, END) lb01v.insert(0, s[6:20]) lb01.grid(sticky=W,row=1,column=1) lb01v.grid(row=1,column=2) lb02=Label(root,text="sequence2") lb02v=Entry(root,textvariable=edit2,width=20) lb02v.delete(0, END) lb02v.insert(0, s[0:6]) lb02.grid(sticky=W,row=2,column=1) lb02v.grid(row=2,column=2) root.mainloop()
-
Waraba almost 12 yearsThanks Bryan I'll try to figure this out