-1

I am trying to interactively validate an entry widget in tkinter to only allow the user to enter characters in the alphabet. I have already read a very popular thread (Interactively validating Entry widget content in tkinter) and from that I have tried to figure out my solution but I just cannot seem to get it working. In the comments of that thread was a solution that only allowed numbers, I have used that for one area of my program and it works perfectly! Code here:

from tkinter import *

root = Tk()

def testVal(inStr,i,acttyp):
    ind=int(i)
    if acttyp == '1': #insert
        if not inStr[ind].isdigit():
            return False
    return True

entry = Entry(root, validate="key")
entry['validatecommand'] = (entry.register(testVal),'%P','%i','%d')
entry.pack()

root.mainloop()

I would like a solution like this, with the only change being that it accepts letters instead of numbers. Any help appreciated

Cœur
  • 37,241
  • 25
  • 195
  • 267
JoeW373
  • 59
  • 1
  • 11

1 Answers1

2

Here's the solution you're looking for:

def testVal(inStr,i,acttyp):
    ind=int(i)
    if acttyp == '1': #insert
        if not inStr[ind].isalpha():
            return False
    return True

Heres some other things which might be useful:

  • .isdigit() tests if a string is an integer
  • .isalpha() tests if a string contains only letters
  • .isalnum() tests if a string contains only letters and numbers
  • .isupper() tests for uppercase
  • .islower() tests for lowercase

For other datatypes you can use isinstance(), for example isinstance("34.5", float) will return True

Source: https://docs.python.org/3/library/stdtypes.html

Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
  • thank you it works great, I wasn't aware of isalpha() i tried ischar() earlier as I guessed that might work as it seemed logical. – JoeW373 Nov 22 '16 at 12:58