vsav vsav - 1 year ago 87
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
). How would I do that in TKinter?


Answer Source

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.insert(tk.INSERT, txt)

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download