Dec-01-2024, 07:30 AM
Hello, I have been struggling with this problem for some time now. The code below is supposed to highlight text added to the text widget if the "bg_color" parameter is not None. No coloring appears, but if additional lines are added afterward, color may fill the remainder of the last line. I have determined that this occurs because the self.text_area.index(tk.END) erroneously displays the end of the text as being at the beginning of the next line, even if there is no next line. How do I modify this function to highlight the text correctly?

def update_text(self, text, clear_first, bg_color=None): if clear_first: self.text_area.delete(1.0, tk.END) # Clear the text area # Capture the starting index start_index = self.text_area.index(tk.END) print(self.text_area.index(tk.END)) # Insert the new text self.text_area.insert(tk.END, text) # Capture the ending index end_index = self.text_area.index(tk.END) print(self.text_area.index(tk.END)) if bg_color: # Apply a tag with the background color tag_name = f"bg_color_{randint(1, 10000)}" # Create a unique tag name self.text_area.tag_add(tag_name, start_index, end_index) self.text_area.tag_config(tag_name, background=bg_color)