Neil
Neil

Reputation: 796

Highlight the entire line length in Tkinter Text widget

This example works fine except that I want the highlighted region to span the width of the Text widget. My first thought was to pad the string with spaces using ljust but as the Text widget is going to be populated with different font types it's not going to work.

Is there a way of highlighting an entire line?

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()

Upvotes: 1

Views: 1160

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386190

Your highlight needs to include the newline character in order to span the full width of the widget. Add "+1c" (plus one character) to your second index:

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

Upvotes: 3

Neil
Neil

Reputation: 796

using +1lines seems to work. I changed the two functions to

def highlight(n):
    text.tag_add("highlight", "{}.0".format(n), "{}.0+1lines".format(n))

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

and it seems to work fine.

Upvotes: 0

Related Questions