【发布时间】:2020-07-22 03:39:36
【问题描述】:
我创建了一个搜索函数来解析滚动文本框中的文本,它会找到第一个条目,我想添加一个函数来查找与按钮匹配的下一个单词。我找到了一个post,它有类似的东西,我尝试在我的代码中复制它,但我认为它是受我用来解析滚动文本框的跟踪函数的影响,因为字母被输入到输入框中。我假设我必须在next_match() 函数中使用tag_nextrange。谁能引导我走向正确的方向?
提前致谢!
我的代码如下所示:
def find_text(event):
def get_text(var, indx, mode):
word = my_var.get()
start = '1.0'
results_text.tag_remove('found', start, END)
if word:
start = results_text.search(word, start, nocase=1, stopindex=END)
last = '%s+%dc' % (start, len(word))
results_text.tag_add('found', start, last)
results_text.tag_config('found', background='yellow')
def next_match():
#This is what I tied but doesn't work.
while 'found' in results_text.tag_names('found'):
n_match = results_text.tag_nextrange('found', END)
if n_match:
results_text.mark_set('found', n_match[0])
results_text.see('found')
my_var = StringVar()
my_var.trace_add('write', get_text)
findstr = Toplevel()
findstr.wm_title("Find")
findstr.wm_iconbitmap("cs_icon.ico")
findstr.resizable(width = False, height = False)
find_label = Label(findstr, text="Enter your search query:", font=("Helvetica", 12))
find_label.grid(row=0, column=0,columnspan=3, sticky='nsew')
find_entry = Entry(findstr, bd=4, textvariable=my_var, width=100)
find_entry.grid(row=1, column=0, columnspan=3,padx=10, sticky='nsew')
find_entry.focus()
next_btn = Button(findstr, text="Next", width=20, command=next_match)
next_btn.grid(row=2, column=2, padx=10, pady=5, sticky='e')
#Binds Ctrl + f key to find_text function.
root.bind("<Control-f>", find_text)
【问题讨论】:
-
@stovfl 完成。让我知道这是否更清楚。
-
@stovfl 我在
if next_match:中打错了字,我将其更正为if n_match:。至于def find_text,它确实有效。它将找到第一个匹配的单词并突出显示背景黄色。我曾经在那里有一个while循环来突出显示文本框中的所有单词,但我删除了它以找到第一个实例。 -
好的,你应该只在函数外使用
def get_text(...makestartglobal 和 initstart = '1.0'。最后找到的索引设置为start = ....
标签: python python-3.x tkinter