Using Stringvar Data As A List
I've been following this website for a while. It is really helpful. So, thanks for all the useful tips. I've been searching for this answer for the past two weeks without any succe
Solution 1:
To restrict the type/number of characters that can be typed into an entry widget, you can use the entry validatecommand. Here is an example to allow only letters and another one to restrict the entry to 4 digits:
from tkinter import Tk, Entry, Label
defonly_letters(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion # only if the inserted character char is a letterreturn char.isalpha()
else:
# allow deletionreturnTruedefonly_numbers_max_4(action, new_text):
if action == "1":
return new_text.isdigit() andlen(new_text) <= 4else:
returnTrue
root = Tk()
# register validate commands
validate_letter = root.register(only_letters)
validate_nb = root.register(only_numbers_max_4)
Label(root, text="Only letters: ").grid(row=0, column=0)
e1 = Entry(root, validate="key", validatecommand=(validate_letter, '%d', '%S'))
# %d is the action code and %S the inserted/deleted character
e1.grid(row=0, column=1)
Label(root, text="Only numbers, at most 4: ").grid(row=1, column=0)
e2 = Entry(root, validate="key", validatecommand=(validate_nb, '%d', '%P'))
# %P is the new content of the entry after the modification
e2.grid(row=1, column=1)
root.mainloop()
For more details on entry validation, see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
Post a Comment for "Using Stringvar Data As A List"