0

In my python tkinter program, in which the user is entering text into a text widget, my program is supposed to compare two texts (one which is given, and another which the user is typing in said entry widget). After comparing texts, it is supposed to turn characters that do not match with the initial given string red.

for index in range(len(self.user_input.get(1.0, "end-1c"))):  # index is index of user string
        if self.user_input.get("1.0", "end")[index] != self.sentence.cget("text")[index]:
            self.mistakes += 1
            self.user_input.tag_add("mistake", index)
            self.user_input.tag_config("mistake", foreground="red")
        else:
            self.user_input.tag_add("correct", index)
            self.user_input.tag_config("correct", foreground="black")

When I execute this loop, it should loop through the entered string (which is always of <= length of the given string) and determine any incorrect characters. Given a character is incorrect, it becomes red, and given it is correct, it stays black.

The problem occurs in self.user_input.tag_add("correct", index) (as seen in the console) and it says there is a _tkinter.TclError: bad text index "0" . In my program, the index I am trying to access exists. This error occurs wherever I first execute the tag_add and tag_configure commands.

Why does this error occur? Is there any fixes to solve this?

  • 1
    `range(len(X))` gives integers that would be suitable for indexing into a Python list - but a Text widget doesn't work that way at all. It wants indexes as strings in *line*.*column* form, with the line starting at 1, and the column starting at 0, along with several options to move the index relative to such a position. I believe you can use `f"1.0+{index}c"` to turn your ints into an index that will work with `tag_add()`, even if the text spans multiple lines. – jasonharper Feb 26 '23 at 02:33

0 Answers0