如何在Tkinter文本框中高亮非空格文本?Python3.8实现疑问
问题:Tkinter文本框仅高亮单词不高亮空格的实现问题
我是Python 3.8新手,想遍历Tkinter文本框的单词与行,实现仅高亮单词、不高亮空格的效果。Tkinter的Text组件get()方法采用特殊索引规则:第一行从1.0开始,第二行从2.0开始。我尝试转换索引但无法高亮全部文本,以下是我的代码:
from tkinter import * import tkinter core = Tk() scroll = Scrollbar(core) txt = Text(core, height = 35, width =85, yscrollcommand = scroll.set, \ font =('bold',15),cursor="plus #aab1212" \ ) # txt1.place(x=980, y=37) scroll.config(command = txt.yview) # scroll1.config(command = txt.xview) scroll.pack(side=RIGHT, fill=Y) txt.pack(side="right") def get_index(): l = [] for i,w in enumerate(txt.get('1.0', 'end-1c').splitlines()): l.append(w) i = i + 1.1 print(i,w) if i < 10: x = 1 + float(0) / 10 txt.tag_add("start", x) txt.tag_config("start", background= "yellow", foreground= "black") print(l) for w,i in enumerate(l): print(i) button1 = Button(text = 'index',command=get_index) button1.place(x = 30, y = 50, height = 30, width = 150) core.mainloop()
解决思路与代码实现
核心是逐行处理文本,对每行内的单词单独计算起始和结束索引,再给单词添加高亮标签,跳过空格部分。
修正后的代码
from tkinter import * core = Tk() scroll = Scrollbar(core) txt = Text(core, height=35, width=85, yscrollcommand=scroll.set, font=('bold',15), cursor="plus #aab1212") scroll.config(command=txt.yview) scroll.pack(side=RIGHT, fill=Y) txt.pack(side="right") def highlight_words(): # 清除之前的高亮标签,避免重复叠加 txt.tag_remove("word_highlight", "1.0", END) txt.tag_config("word_highlight", background="yellow", foreground="black") # 获取所有文本并按行分割 content = txt.get('1.0', 'end-1c').splitlines() # 遍历每行,行号从1开始对应Tkinter的索引规则 for line_num, line_content in enumerate(content, start=1): current_pos = 0 # 按空格分割出单词,自动过滤空字符串(连续空格的情况) for word in line_content.split(): # 找到单词在当前行的起始位置 start_idx = line_content.find(word, current_pos) if start_idx == -1: continue # 拼接Tkinter认可的索引格式:行号.字符偏移量 start_index = f"{line_num}.{start_idx}" end_index = f"{line_num}.{start_idx + len(word)}" # 给单词添加高亮标签 txt.tag_add("word_highlight", start_index, end_index) # 更新当前位置,避免重复匹配同一个单词 current_pos = start_idx + len(word) button1 = Button(text='高亮单词', command=highlight_words) button1.place(x=30, y=50, height=30, width=150) core.mainloop()
关键说明
- 先清除旧标签:避免多次点击按钮后高亮样式重复叠加
- 逐行匹配行号:用
enumerate(content, start=1)直接获取对应Tkinter规则的行号 - 精准定位单词:计算每个单词在该行的字符偏移量,拼接成
行号.偏移量的标准索引格式 - 自动跳过空格:通过
split()分割文本时,会自动忽略连续空格,只处理实际的单词内容
内容的提问来源于stack exchange,提问作者Kishan
相关产品推荐
相关产品推荐

