gpt4 book ai didi

python - 如何在 Tkinter 文本小部件中突出显示单词或字母表?

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:15 24 4
gpt4 key购买 nike

假设这是我需要使用的程序,我希望 find() 函数在被调用时从文本小部件中选择单词“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()

当按下按钮“Find Hello”时,小部件将如下所示。 Text Widget

最佳答案

我做了一个简单的程序来选择文本中的所有 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()

输出:

enter image description here

我用过这个 answer寻求帮助。

关于python - 如何在 Tkinter 文本小部件中突出显示单词或字母表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com