Tkinter Text Spell Check
When writing a text program, if you want to make the program more complete you can design a spell check function, in fact, in this section does not introduce the new features of the Text control, which is considered an application of the topic program.
Example#1
Design a small dictionary myDict.txt, then compare each word in the Text control with the word in the dictionary, and if there is a word that does not match, display the word in red. This program has two other function buttons, Spell check
button to perform spell check and Clear
button to change the words shown in red to normal display.
myDict.txt:
['Five', 'Hundred', 'Miles', 'If', 'you', 'miss', 'the', 'rain', 'I', 'am','on','You', 'will', 'knw', 'that', 'I', 'am', 'gone','You', 'can', 'hear', 'the', 'whistle','blw', 'A', 'hunded', 'miles,']
Code:
from tkinter import *
def spellingCheck():
text.tag_remove("spellErr","1.0",END)
textwords = text.get("1.0",END).split()
print("Dictionary Content\n",textwords)
# print("#############dicts##############\n",dicts)
# print("#############dicts##############")
startChar = ("(")
endChar = (".", ",", ":", ";", "?", "!", ")")
start = "1.0"
for word in textwords:
if word[0] in startChar:
word = word[1:]
if word[-1] in endChar:
word = word[:-1]
if (word not in dicts and word.lower() not in dicts):
print("error",word)
pos = text.search(word,start,END)
text.tag_add("spellErr",pos,"%s+%dc"%(pos,len(word)))
pos = "%s+%dc" %(pos,len(word))
def clrText():
text.tag_remove("spellErr","1.0",END)
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
# create toolbar
toolbar = Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)
chkBtn = Button(toolbar,text="Spell check",command=spellingCheck)
chkBtn.pack(side=LEFT,padx=5,pady=5)
clrBtn = Button(toolbar,text="Clear",command=clrText)
clrBtn.pack(side=LEFT,padx=5,pady=5)
# create Text
text = Text(root,undo=True)
text.pack(fill=BOTH,expand=True)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I am on,\n")
text.insert(END,"You will knw that I am gone.\n")
text.insert(END,"You can hear the whistle blw\n")
text.insert(END,"A hunded miles,\n")
text.tag_configure("spellErr", foreground="red")
with open("myDict.txt","r") as dictObj:
dicts = dictObj.read().split('\n')
root.mainloop()
Output:
This program will first list the contents of the dictionary, and if it finds a word that doesn’t match, it will list the word in the Python Shell window, and here are the results.