【问题标题】:Python search for next word in a Scrolled text box using tkinterPython使用tkinter在滚动文本框中搜索下一个单词
【发布时间】: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(... make start global 和 init start = '1.0'。最后找到的索引设置为start = ....

标签: python python-3.x tkinter


【解决方案1】:

我前段时间想通了。看起来对我有用的是创建一个单独的列表(search_list)来充当位置计数器并让它增加和标记单词。我将新列表的声明与我创建的另一个可变列表放在代码的开头。另外,对于那些好奇的人,我将var, indx, and mode 传递给get_text 函数,以通过跟踪函数获取实时搜索结果。我希望这对尝试实现此功能的人有用:

def get_text(var, indx, mode):
    word = my_var.get()
    search_list.clear()
    start = '1.0'
    results_text.tag_remove('next', '1.0', END)
    results_text.tag_remove('found', start, END)
    global matches_found
    matches_found = 0
    if word:
        while 1:
            start = results_text.search(word, start, regexp=True ,nocase=1,
                                        stopindex=END)
            if not start: break
            last = '%s+%dc' % (start, len(word))
            results_text.tag_add('found', start, last)
            matches_found += 1
            start = last
            results_text.tag_config('found', background='yellow')
    total_label.config(text=f"0:{str(matches_found)}")

def next_match():
    results_text.tag_remove('next', '1.0', END)
    end_search_label.config(text="")
    word = find_entry.get()
    count_pos = 0
    if word:
        start = "1.0" if search_list == [] else search_list[-1]
        start = results_text.search(word, start, nocase=1, stopindex=END)
        last = '%s+%dc' % (start, len(word))
        try:
            results_text.tag_add('next', start, last)
            results_text.tag_config('next', background='cyan',foreground='black',
                                    underline=1)
            counter_list = start.split('.')
            results_text.mark_set("insert", "%d.%d" % 
                                  (int(counter_list[0]),int(counter_list[1])))
            results_text.see(float(int(counter_list[0])))
            search_list.append(last)
            for i in search_list:
                count_pos += 1
            total_label.config(text=f"{str(count_pos)}:{str(matches_found)}")
        except:
            end_search_label.config(text="Search complete. No further matches",
                                    anchor='w')
            search_list.clear()

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2017-10-25
    • 2019-08-12
    • 2014-09-09
    • 2015-06-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    相关资源
    最近更新 更多