-1

I am actually trying to make a python coding editor, for that I need to make a color-coding system. For example: 'def', 'or', 'if', 'elif', 'else', 'import' etc. should be in different colors as they are commands. Something like this:

from tkinter import *
import threading

def colorcommands():
    while True:
        a = textArea.get(0.0, END)
        for f in ["def", "or", "and", "if", "import", "else"]:
            textArea.replace(f, (f, fg="red"))

master = Tk()

textArea = Text()
textArea.pack()

threading.Thread(target=colorcommands).start()

master.mainloop()

But obviously this gives me an error, as there is no such command as this. Can anyone help me out?

Ultra
  • 21
  • 2
  • `0.0` is an invalid index for two reasons. The first character is `"1.0"`, and indexes should be strings. `0.0` works because tkinter will translate it to `"1.0"`, but using floating point numbers is technically incorrect. – Bryan Oakley May 20 '20 at 12:25
  • Your question is unclear. The title says you want to replace the text but the body says you want to highlight the text. – Bryan Oakley May 20 '20 at 12:28

2 Answers2

0

This is the final code and it works perfectly:

from tkinter import *
import threading, keyword

def Process():
    while True:
        a = textArea.get(0.0, END)
        b = a.split("\n")
        words = {}
        for f in range(1, len(b)+1):
            bb = b[f-1].split(" ")
            bb2 = []
            for ff in range(1, len(bb)+1):
                try:
                    bb3 = words[bb[ff-1]]
                    bb3.append(str(f) + "." + str(len(" ".join(bb2))) + " - " + str(f) + "." + str(len(" ".join(bb2)) + len(bb[ff-1]) + 1))
                except:
                    words[bb[ff-1]] = [str(f) + "." + str(len(" ".join(bb2))) + " - " + str(f) + "." + str(len(" ".join(bb2)) + len(bb[ff-1]) + 1)]
                bb2.append(bb[ff-1])

        for f3 in words:
            if f3 in keyword.kwlist:
                for ff in words[f3]:
                    wordss = ff.split(" - ")
                    textArea.tag_add("code", wordss[0], wordss[1])
                    textArea.tag_config("code", foreground="red")

master = Tk()

textArea = Text()
textArea.pack()

threading.Thread(target=Process).start()

master.mainloop()

Thank You Everyone! :D

Ultra
  • 21
  • 2
-1

I believe you can accomplish this through the use of tags. Tags can be used to alter certain parts of Text in Tkinter. First up is actually configuring the tag with tag_configure, then applying it with tag_add. You'll have to look the details of the syntax yourself.

I found another answer by someone who had the same question. In the accepted answer, you can find an example code. Run that and see if it works for you. How to change the color of certain words in the tkinter text widget?

Storm Claw
  • 59
  • 2
  • 8