Python 查找函数每行选择一个匹配项
Python find function selects one match per line
我正在尝试使用 python 制作一个简单的文本编辑器。我现在正在尝试创建一个查找功能。这就是我得到的:
def Find():
text = textArea.get('1.0', END+'-1c').lower()
input = simpledialog.askstring("Find", "Enter text to find...").lower()
startindex = []
endindex = []
lines = 0
if input in text:
text = textArea.get('1.0', END+'-1c').lower().splitlines()
for var in text:
character = text[lines].index(input)
start = str(lines + 1) + '.' + str(character)
startindex.append(start)
end = str(lines + 1) + '.' + str(character + int(len(input)))
endindex.append(end)
textArea.tag_add('select', startindex[lines], endindex[lines])
lines += 1
textArea.tag_config('select', background = 'green')
这将成功突出显示与用户输入相匹配的带有绿色背景的单词。但问题是,它只突出显示每一行的第一个匹配项,如您所见 here.
我想让它突出显示 所有 个匹配项。
完整代码在这里:https://pastebin.com/BkuXN5pk
推荐使用文本小部件的内置搜索功能。使用 python3.
显示
from tkinter import *
root = Tk()
textArea = Text(root)
textArea.grid()
textArea.tag_config('select', background = 'green')
f = open('mouse.py', 'r')
content = f.read()
f.close()
textArea.insert(END, content)
def Find(input):
start = 1.0
length = len(input)
while 1:
pos = textArea.search(input, start, END)
if not pos:
break
end_tag = pos + '+' + str(length) + 'c'
textArea.tag_add('select', pos, end_tag)
start = pos + '+1c'
Find('display')
root.mainloop()
我正在尝试使用 python 制作一个简单的文本编辑器。我现在正在尝试创建一个查找功能。这就是我得到的:
def Find():
text = textArea.get('1.0', END+'-1c').lower()
input = simpledialog.askstring("Find", "Enter text to find...").lower()
startindex = []
endindex = []
lines = 0
if input in text:
text = textArea.get('1.0', END+'-1c').lower().splitlines()
for var in text:
character = text[lines].index(input)
start = str(lines + 1) + '.' + str(character)
startindex.append(start)
end = str(lines + 1) + '.' + str(character + int(len(input)))
endindex.append(end)
textArea.tag_add('select', startindex[lines], endindex[lines])
lines += 1
textArea.tag_config('select', background = 'green')
这将成功突出显示与用户输入相匹配的带有绿色背景的单词。但问题是,它只突出显示每一行的第一个匹配项,如您所见 here.
我想让它突出显示 所有 个匹配项。
完整代码在这里:https://pastebin.com/BkuXN5pk
推荐使用文本小部件的内置搜索功能。使用 python3.
显示from tkinter import *
root = Tk()
textArea = Text(root)
textArea.grid()
textArea.tag_config('select', background = 'green')
f = open('mouse.py', 'r')
content = f.read()
f.close()
textArea.insert(END, content)
def Find(input):
start = 1.0
length = len(input)
while 1:
pos = textArea.search(input, start, END)
if not pos:
break
end_tag = pos + '+' + str(length) + 'c'
textArea.tag_add('select', pos, end_tag)
start = pos + '+1c'
Find('display')
root.mainloop()