Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use tkinter tag_config? Python 3.7.3

So I wanted to make a text editor and I've gotten stuck on this part, I want it to change the color of a certain word thats typed in in real time, for example: Lets say I type print I want it to automatically change the foreground color from the default black color to lets say blue. I Don't really know if you have to use tag_configure to do this but if so can someone please help me work it, thanks.

Code:

from tkinter import *

root = Tk()

text = Text(root)
text.grid(row=0)

def Event(event):
    text.tag_configure("print", foreground="blue")

#This is a KeyBind to trigger the Function: Event
root.bind("<Return>", Event)

root.mainloop()
like image 717
MoziakBeats Avatar asked Feb 02 '26 13:02

MoziakBeats


1 Answers

If you want to change the color of text as you're typing it in, you need to do a few things:

  1. define a tag with the desired coloration. You're already got:

    text.tag_configure("print", foreground="blue")

which works. You probably want to be able to trigger other events which change the color to apply for the newly typed text, or your editor will be quite boring. You can have a few buttons with a different color for each, etc. You'll probably want multiple tags, because if you change the config of the "print" tag, everything that is already tagged with that tag name will change to match the new config.

  1. then you have to apply the tag to the text as you're typing it in. There are probably a few ways to do this, but you can process each character as it's typed by setting up a binding for "<Key>" events. Each time the event is triggered, because a new char has been typed, go back and apply the tag "print" to that character.

So, something along the lines of:

root.bind("<Key>", on_key)

along with:

def on_key(event=None):
    text.tag_add("print", "INSERT - 1c", "INSERT")

That should roughly give you what you want, but as it's set up, it still won't be too interesting. You can have multiple tags, each configured to look visually different (different foreground and background colors, etc), and apply different tags to what you're typing in, as you see fit.

INSERT is a special Text widget mark which represents where the insertion point/cursor is in the widget. As you type, INSERT keeps moving to the right, always just after what you've typed. So, "INSERT - 1c" is the previous location and points to the character that was just typed.

like image 134
Gary02127 Avatar answered Feb 04 '26 01:02

Gary02127



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!