vsav vsav - 6 months ago 35
Python Question

Highlighting a specific position of a string?

In my TKinter GUI I am trying to highlight a specific character in my text string. I have a string, which I declare as

Stringvar = StringVar()
. Lets say I wanted to highlight the first character of
Stringvar
(i.e.
Stringvar[0]
). How would I do that in TKinter?

Thanks!

Answer

Here's a simple script that will highlight text based on the character positions that you give it.

Run the script, hit the 'highlight' button then input your start and end positions in the format 1.0-1.0 .

The first digit refers to the line number. The digit after the decimal place refers to the character position in the line.

import Tkinter as tk
import tkSimpleDialog

def highlight():
    var = tkSimpleDialog.askstring("Text Highlighter", "format: x.x-x.x")
    a,b = var.split("-")
    aText.tag_add("bt", a, b)

txt = "First line of text \nSecond line of text \nThird line of text"

lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aText.insert(tk.INSERT, txt)

aButton = tk.Button(lord, text="highlight", command=highlight)
aButton.grid()

aText.tag_config("bt", background="yellow")

lord.mainloop()
Comments