【问题标题】:How to get the index of word being searched in tkinter text box [duplicate]如何获取在tkinter文本框中搜索的单词索引[重复]
【发布时间】:2014-09-09 05:52:15
【问题描述】:

我是 python 新手。我正在使用 Tkinter 制作 ui。 我有一个文本框,用户可以在其中写多行。 我需要在该行中搜索某些单词并突出显示它。

目前,当我在其中搜索所需的单词并尝试使用“tag_configure”和“tag_add”着色时,我收到“错误索引”错误。 在网上阅读某些页面后,我了解到“tag_add”中使用的开始和结束索引的格式为“row.column”[如果我在某处出错,请纠正我]。谁能帮助我直接从 tkinter ui 获取这种格式的索引以进行突出显示。

【问题讨论】:

标签: python tkinter


【解决方案1】:

它必须是浮点数 - 例如文本中的第一个字符是 1.0(不是字符串 "1.0")


编辑:我犯了错误。它可以是字符串——它必须是字符串,因为1.1 和1.10 是相同的浮点数(如Bryan Oakley 所说)——但我留下了这个工作示例。


from Tkinter import *

#------------------------------------

root = Tk()

#---

t = Text(root)
t.pack()

t.insert(0.0, 'Hello World of Tkinter. And World of Python.')

# create tag style
t.tag_config("red_tag", foreground="red", underline=1)

#---

word = 'World'

# word length use as offset to get end position for tag
offset = '+%dc' % len(word) # +5c (5 chars)

# search word from first char (1.0) to the end of text (END)
pos_start = t.search(word, '1.0', END)

# check if found the word
while pos_start:

    # create end position by adding (as string "+5c") number of chars in searched word 
    pos_end = pos_start + offset

    print pos_start, pos_end # 1.6 1.6+5c :for first `World`

    # add tag
    t.tag_add('red_tag', pos_start, pos_end)

    # search again from pos_end to the end of text (END)
    pos_start = t.search(word, pos_end, END)

#---

root.mainloop()

#------------------------------------

【讨论】:

  • 您的“它必须是浮点数”的说法不正确。它不是浮点数,它是“line.character”形式的字符串。它可能看起来像一个浮点数,但它不是。例如,浮点数 1.1 和 1.10 代表相同的数字,但它们不代表文本小部件中的相同字符。
  • 你说得对 - 现在我看到了我的错误 1.1 and 1.10 - 我一直使用 float 但只使用 1.0 来清除所有文本。
  • 谢谢大家..我能够在这篇文章的帮助下做到这一点..stackoverflow.com/questions/3732605/advanced-tkinter-text-box
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多