简体   繁体   English

我如何突出显示 tkinter 文本小部件中的某些单词?

[英]How i can highlight some words in a tkinter Text widget?

this is my first question here... Im doing a project that highlight words entered in a list How i can highlight it?这是我的第一个问题...我正在做一个突出显示列表中输入的单词的项目我如何突出显示它? my code:我的代码:

   import tkinter
   root = tkinter.Tk()
   words = ["Potatos","Tomatoes","Carrots"]
   box = tkinter.Text(root)
   box.pack()
   root.mainloop()

How i can highlight the text of a color if i enter a word that is in the words list?如果我输入单词列表中的单词,我如何突出显示颜色的文本? im sorry if i sound stupid but im a novice对不起,如果我听起来很愚蠢,但我是新手

Try this:尝试这个:

  • Add highlight_text() function.添加highlight_text() function。
  • Add clear() function.添加clear() function。
  • Add Button for highlight.添加Button以突出显示。
  • Add Button for clear.添加Button以清除。
  • Remove brace bracket that you don't needed List删除不需要的大括号List

Modified code:修改后的代码:

import tkinter
root = tkinter.Tk()

def highlight_text():
    try:
        box.tag_add("start", "sel.first", "sel.last")        
    except tk.TclError:
        pass

def clear():
    box.tag_remove("start",  "1.0", 'end')
       
words = "Potatos","Tomatoes","Carrots"
        
box = tkinter.Text(root, width=25, height=5)
box.insert(tkinter.INSERT, words)
box.pack()
box.tag_configure("start", background="black", foreground="red")

highlight_btn = tkinter.Button(root, text="Highlight", command=highlight_text)
highlight_btn.pack(side=tkinter.LEFT)
       
clear_btn = tkinter.Button(root, text="Clear", command=clear)
clear_btn.pack(side=tkinter.LEFT)

root.mainloop()

Output before, highlight and clear: Output之前,高亮清除:

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM