1

In an attempt to create a Python Entry widget with limited input(3 or 4 characters), I found this

Knowing nothing yet about validation, my question is this: can the 'subclass' for max length in that tutorial be used as its own class, referencing the entry widget as its parent instead of 'ValidatingEntry', or is all the legwork above it (validating) necessary? Is there any shorter way to accomplish this?

Then I saw this question and its answer:

Considering doing something like that. Then I discovered the builtin 'setattr' function. Is it possible to apply this to a new instance of the class 'Entry' and use it to limit characters?

I should clarify- I'm trying to apply this limit to 3 entry widgets- two with a 3 character limit and one with a 4 character limit (a phone number)

Thanks.

dstrants
  • 7,423
  • 2
  • 19
  • 27

1 Answers1

0

Regarding your stated concern of length validation in an Entry widget. An example of input length validation.

# further reference
# http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
import tkinter as tk

root = tk.Tk()

# write the validation command
def _phone_validation(text_size_if_change_allowed):
    if len(text_size_if_change_allowed)<4:
        return True 
    return False

# register a validation command
valid_phone_number = root.register(_phone_validation)

# reference the validation command
entry = tk.Entry(validate='all',
                 validatecommand=(valid_phone_number,'%P' ))
entry.pack()
root.mainloop()

suggestion in response to comment on focus switching between entry widgets, change validate 'all'-> 'key', and use focus_set()

import tkinter as tk

root = tk.Tk()

# write the validation command
def _phone_validation(text_size_if_change_allowed):
    if len(text_size_if_change_allowed) == 3:
        entry2.focus_set()
    if len(text_size_if_change_allowed)<4:
        return True 
    return False

# register a validation command
valid_phone_number = root.register(_phone_validation)

# reference the validation command
entry = tk.Entry(validate='key',
                 validatecommand=(valid_phone_number,'%P' ))
entry2 = tk.Entry()

entry.pack()
entry2.pack()
root.mainloop()
R Spark
  • 323
  • 1
  • 4
  • 11
  • Thanks! I'll give that a shot if I can apply it correctly! Validation is still pretty confusing thus far. Alternately, is there an 'easy' way to simply set focus to a different Entry widget upon reaching a certain number of characters? If I'm beginning to understand validation correctly, it seems like this method would also require it...? – Michael Sibille Mar 31 '18 at 06:09