我一直在尝试在Tkinter GUI上进行按钮检查,以将输入的文本搜索到特定词的文本小部件中并使其显示为红色,我设法使用以下代码来做到这一点:
list_of_words = ["foo", "bar`enter code here`"]
def check():
global counter
text.tag_remove('found', '1.0', END)
idx = '1.0'
x = 0
while True:
idx = text.search(list_of_words[x], idx, nocase=1, stopindex=END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(list_of_words[x]))
text.tag_add('found', idx, lastidx)
idx = lastidx
text.tag_config('found', foreground='red')
counter += 1
print counter
但是,我需要能够在输入中搜索list_of_words列表中的所有单词,并将它们全部显示为红色。有什么办法吗?
您的代码不会递增,x
因此,如果存在第一个单词,则while循环将永远不会终止。但是,它确实会增加全局变量,但counter
没有明显的原因。
为什么不简单地使用for循环遍历目标词列表呢?内部while循环将在文本小部件中搜索每个单词的所有实例,并将其标记为突出显示。while循环的终止条件是在窗口小部件中找不到当前单词。然后,在标记所有单词之后,设置其颜色。
def check():
text.tag_remove('found', '1.0', END)
for word in list_of_words:
idx = '1.0'
while idx:
idx = text.search(word, idx, nocase=1, stopindex=END)
if idx:
lastidx = '%s+%dc' % (idx, len(word))
text.tag_add('found', idx, lastidx)
idx = lastidx
text.tag_config('found', foreground='red')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句