Tkinter Text 拼写检查
在编写文字程序时,如果想要让程序更完整可以设计拼写检查功能,其实在本节并没有介绍Text控件的新功能,这算是一个应用的专题程序。
示例1
设计一个小字典myDict.txt,然后将Text控件的每个单词与字典的单词做比较,如果有不符的单词则用红色显示此单词。这个程序另外两个功能按钮,Spell check
按钮可以执行拼写检查,Clear
按钮可以将红色显示的字改为正常显示。
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,']
代码:
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")
# 建立工具栏
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)
# 建立Text
text = Text(root,undo=True)
text.pack(fill=BOTH,expand=True)
text.insert(END,"Five Hundred Miles\n") # 插入时同时设置Tag
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()
输出:
这个程序在执行时会先列出字典内容,如果找到不符单词会在Python Shell窗口列出此单词,下面是执行结果。