首页 > 解决方案 > 在 Tkinter Text 小部件中突出显示整个行长

问题描述

除了我希望突出显示的区域跨越文本小部件的宽度之外,此示例工作正常。我的第一个想法是使用空格填充字符串,ljust但由于 Text 小部件将填充不同的字体类型,因此它不起作用。

有没有办法突出整行?

import tkinter as tk

def highlight(n):
    text.tag_add("highlight", "{}.0".format(n), "{}.end".format(n))

def remove_highlight(n):
    text.tag_remove("highlight", "{}.0".format(n), "{}.end".format(n))

root = tk.Tk()

text = tk.Text(root, width=30, height=3, wrap=None)
text.pack()

text1 = "text"
text2 = "text2"

text.insert(tk.INSERT, "{}\n".format(text1))
text.insert(tk.INSERT, text2)

text.tag_configure("highlight", background="grey")
text.tag_configure("normal", font=("Arial", 12))
text.tag_configure("large", font=("Arial", 18))

text.tag_add("normal", "1.0", "1.end")
text.tag_add("large", "2.0", "2.end")

text.tag_bind("normal", "<Enter>", lambda event, n = 1: highlight(n))
text.tag_bind("normal", "<Leave>", lambda event, n=1: remove_highlight(n))
text.tag_bind("large", "<Enter>", lambda event, n = 2: highlight(n))
text.tag_bind("large", "<Leave>", lambda event, n=2: remove_highlight(n))

text.configure(state="disabled")

root.mainloop()

标签: pythontkinter

解决方案


您的突出显示需要包含换行符才能跨越小部件的整个宽度。将“+1c”(加一个字符)添加到您的第二个索引:

text.tag_add("highlight", "{}.0".format(n), "{}.end+1c".format(n))

推荐阅读