Python Forum
[Tkinter] color a string of characters in tkinter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] color a string of characters in tkinter
#2
Requires python 3.6 or newer

This code will allow you to color and set background for any portion of any line
def highlight_text(tag_name, lineno, start_char, end_char, bg_color=None, fg_color=None):
    txtwidget.tag_add(tag_name, f'{lineno}.{start_char}', f'{lineno}.{end_char}')
    txtwidget.tag_config(tag_name, background=bg_color, foreground=fg_color)
And used in example:
import tkinter as tk

data = """'This is line 1.'
'This is line 2.'
'Yet another line.'
'And finally the last line.'
"""
root = tk.Tk()

txtwidget = tk.Text(root)
for line in data:
    txtwidget.insert(tk.END, line)
txtwidget.pack(expand=1, fill=tk.BOTH)

# adding a tag to a part of text specifying the indices
def highlight_text(tag_name, lineno, start_char, end_char, bg_color=None, fg_color=None):
    txtwidget.tag_add(tag_name, f'{lineno}.{start_char}', f'{lineno}.{end_char}')
    txtwidget.tag_config(tag_name, background=bg_color, foreground=fg_color)
    
highlight_text(tag_name='tag1', lineno=1, start_char=1, end_char=5, fg_color='red')
highlight_text(lineno=1, start_char=9, end_char=15, bg_color="black", fg_color='yellow', tag_name='zingo')

root.mainloop()
results:
   

** Note ** added as edit --> This can be modified to work with older versions by replacing f-string's.
Reply


Messages In This Thread
RE: color a string of characters in tkinter - by Larz60+ - Mar-27-2019, 09:56 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter - How can I change the default Notebook border color? TurboC 5 15,001 May-23-2022, 03:44 PM
Last Post: bigmac
  why my list changes to a string as I move to another window in tkinter? pymn 4 2,651 Feb-17-2022, 07:02 AM
Last Post: pymn
  Can't get tkinter button to change color based on changes in data dford 4 3,542 Feb-13-2022, 01:57 PM
Last Post: dford
Question [Tkinter] Can I set background color for each item in tkinter Combobox? water 1 5,228 Dec-10-2020, 07:48 PM
Last Post: Larz60+
  tkinter | Button color text on Click Maryan 2 3,477 Oct-09-2020, 08:56 PM
Last Post: Maryan
  [tkinter] color change for hovering over button teacher 4 8,769 Jul-04-2020, 06:33 AM
Last Post: teacher
  TKINTER - Change font color for night or day Ayckinn 2 3,980 May-24-2020, 09:25 PM
Last Post: Ayckinn
  Tkinter help (color) Florent 2 2,414 Mar-01-2020, 02:59 PM
Last Post: Florent
  Restoring Tkinter widget background to original color pythonprogrammer 1 3,064 Dec-16-2019, 04:59 AM
Last Post: woooee
  Make Label Text background (default color) transparent using tkinter in python barry76 1 24,216 Nov-28-2019, 10:19 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020