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
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 lowercaseFor other datatypes you can use isinstance()
, for example isinstance("34.5", float)
will return True