Skip to content
Advertisement

How do I get hex codes to work with tkinter text boxes? The regular colors like “red”, “yellow” etc works. But not hex

OS: Windows 10

This is my “texter”, it is used to print letter for letter at certain speeds. It takes the text to print, and a text color as arguments. This works perfectly if i write – texter(“Hello there”, “red”)

global charpos
charpos = 1.0
def texter(inserted_text, text_color = "white"):
    global charpos, text
    text.configure(state='disabled')
    charpos = (charpos + 1)
    for char in inserted_text:
        text.configure(state='normal')
        text.insert(charpos, f"{char}", text_color)
        charpos += 1.0
        text.configure(state='disabled')
        waithere(10)

However it stops working and only prints white text when I do something like – texter(“Hello there”, “orange2”)

And “orange2” should be a supported color in tkinter, right?

For instance, this code works perfectly:

texter("[Freya]: ", "yellow")
    texter("Well you don't have a choice!nn")

While these examples do not work, and just prints the white text:

texter("[Freya]: ", "snow")
    texter("Well you don't have a choice!nn")

texter("[Freya]: ", "#8E44AD")
    texter("Well you don't have a choice!nn")

This is my first python project, started learning two or three weeks ago so please excuse any other mistakes in my code. Does anyone have any good ideas to why the most basic colors work, but the tkinter “advanced” colors do not, and hex values do not?

I should also mention the hex colors and advanced colors DO WORK when applied to the tkinter main window, or background colors of the textbox I am using, but not on the actual text inside it. I believe my texter function is the problem, but I cannot figure out what it is since it is working with regular colors such as “yellow”, “blue”, “red”, “black” etc.

Advertisement

Answer

Do you know what that last argument to insert is? it’s tag name, what you should do, is then configure that tag to the color you want, so basically just add text.tag_config(text_color, foreground=text_color) at the end of the function, also I hope that you understand that you don’t need to insert characters individually and you can just do text.insert(charpos, inserted_text, ...) and then just do charpos += len(inserted_text), so the function now should look like:

charpos = 1.0
def texter(inserted_text, text_color = "white"):
    global charpos
    charpos += 1
    text.configure(state="normal")
    text.insert(charpos, inserted_text, text_color)
    text.tag_config(text_color, foreground=text_color)
    text.configure(state="disabled")
    charpos += len(inserted_text)
    waithere(10)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement