Python 如何在Tkinter文本小部件中选择单词或字母表?
假设这是我需要使用的程序,我希望Python 如何在Tkinter文本小部件中选择单词或字母表?,python,tkinter,text,selection,Python,Tkinter,Text,Selection,假设这是我需要使用的程序,我希望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() 当按下“查找Hello”按钮时,小部件将
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()
当按下“查找Hello”按钮时,小部件将如下所示。我制作了一个简单的程序来选择文本中的所有
Hello
s:
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()
输出:
我用它来帮助你。找到单词后,你有突出显示功能吗?你能解释一下这个突出显示功能吗?如果标签的附加值是2.10,float会自动删除“0”。您有什么解决方案吗?@Suparno您可以将其用作字符串,并在需要输入时转换为float。你可以问另外一个问题。事实上我试过了,但没有改变。那么我要问一个单独的问题,谢谢。