如何在Tkinter Text小部件中突出显示单词或字母?

3
假设这是我需要使用的程序,我希望find()函数在调用时能够从Text小部件中选择单词“Hello”-
from Tkinter import *
def find():
    tx.select_word("Hello")
root = Tk()
tx = Text(root)
bu = Button(root, text = "Find Hello", command = find)
tx.pack()
bu.pack()
root.mainloop()

当按下“查找Hello”按钮时,小部件将会显示如下。Text Widget


一旦找到单词,您是否有突出显示功能? - moe asal
1个回答

4
我制作了一个简单的程序来选择文本中的所有Hello
from tkinter import *


def find_nth(haystack, needle, n):                                   #Function to find the index of nth substring in a string
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

def find():
    word = "H"                                                       #Targetted Word  
    text, line = tx.get("1.0",END), 0                                #text getting text of the widget
    text = text.split("\n")                                          #splitting and getting list on the newlines
    for x, i in enumerate(text):                                     #Looping through that list
        if word in i:                                                #if targetted word is in the xth string i of the list
            for e in range(0, i.count(word)):
                index = find_nth(i, word, e+1)                       #Getting the index of the word
                start = float(str(x+1)+"."+str(index))               #Making the indices for tkinter
                end = float(str(x+1)+"."+str(index+len(word)))       #Making the indices for tkinter
                tx.focus()                                           #Focusing on the Text widget to make the selection visible
                tx.tag_add("sel", start, end)                        #selecting from index start till index end
root = Tk()
tx = Text(root)
tx.insert(END, "World Hello World\nHello World Hello Hello\nHello Hello")
bu = Button(root, text = "Find Hello", command = find)
tx.pack()
bu.pack()
root.mainloop()

输出:

在这里输入图片描述

我使用了 这个答案 帮助。


如果tag_add的值类似于2.10,float会自动删除“0”。你有什么解决方案吗? - Suparno
@Suparno 你可以将其作为字符串使用,并在需要输入时转换为浮点数。你可以提出一个单独的问题来询问这个。 - Nouman
实际上我尝试过了,但是没有任何改变。那么我会提出一个单独的问题,谢谢。 - Suparno
@BlackThunder,请问如何为每个选定的单词获取工具提示? - bib
对于工具提示,您需要跟踪鼠标位置以查看它是否在任何选定的单词上方,然后使用顶级窗口创建工具提示。个人建议使用一些基于HTML的UI,例如使用eel框架。 - Nouman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接