close
Python Forum
[Tkinter] textbox compare command not working for me
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] textbox compare command not working for me
#1
for index = "10.5"

why is textbox.compare(index,"==","10.end") TRUE for all values beyond 10.4

I would like to test (textbox.compare) where the end point is to place a string in a textbox at a certain location.
If a given index is to the right of the end of the line -> pad from end to index with spaces then write the string.
If exactly at the end of the line just write (textbox.insert) the string.
If to the left of the end of the line -> delete (textbox.delete) from index to end then write the string.

I would like to understand the correct way to test for the position...this illustrates my issue:

import tkinter as tk
from tkinter import ttk

# create - main parent
window=tk.Tk()
#window attributes
window.title("Testing")
window.attributes("-fullscreen", True)#no top bar on window so can't resize or close window - button to exit
window.config(background="black")

#create Widget
textbox= tk.Text(master=window,
                          height=24,#number of lines on screen
                          width=100,#number of characters per line
                          border=1,#just so I can see the box edges
                          borderwidth=2,#just so I can see the box edges
                          font=("Lucinda",24),
                          background="black",
                          foreground="#55dddd")
textbox.pack()

def init_text_window():#writes a new line character for 24 lines on screen - change if textbox height changes
    for _ in range(0,24):
        textbox.insert("0.0","\n")

test_button=ttk.Button(master=window,
                       text="exit program",
                       command=lambda: window.quit())
test_button.pack()

init_text_window()#done first - places a \n at the end of each line of screen

for i in range (1,10):
    textbox.insert(f"{i}.0","TEST test TEST test")#nonsense text for testing

test_index=textbox.index("8.end")
print(test_index)
for i in range (15,30):
    if textbox.compare(test_index,">",f"8.{i}"):
        print(f"{test_index} tests greater than 8.{i}")
    if textbox.compare(test_index,"==",f"8.{i}"):
        print(f"{test_index} test equal to 8.{i}")
    if textbox.compare(test_index,"<",f"8.{i}"):
        print(f"{test_index} tests less than 8.{i}")
    
#run
window.mainloop()
printed to output screen on VSCode


dmac6809
Reply
#2
In Text, the index cannot be longer than END. If 10.END == 10.5, you cannot go to 10.6. This is reflected in the respose to your test. 10.6 is past 10.END, so it becomes 10.END.

From TkDocs: https://tkdocs.com/tutorial/text.html
Quote:An index past the end of the text (e.g., end + 100c) is interpreted as end.

There is no need for a lambda expression here:
test_button=ttk.Button(master=window,
                       text="exit program",
                       command=lambda: window.quit())
This works the same.
test_button=ttk.Button(master=window, text="exit program", command=window.quit)
Use a lambda expression if you want to change the arguments passed when a function is called. In the code below I use a lambda expression to remove the "event" argument that is passed to functions bound to B1-Motion events. Later I use a lambda to pass an additional argument to the self._type() function call.

I've never used Text.compare() and am having difficulty thinking of a use case. If I were writing my own code to track mouse movement and button presses to do text selection I can see using Text.compare to convert button press/button release indices to selection first/last indices. But I don't have to write that code. The Text widget does the sorting for me, as is shown in the example below.
import tkinter as tk


class TextTest(tk.Tk):
    # A window for learning about the Text wiget index.
    def __init__(self):
        super().__init__()
        self._text = tk.Text(self, height=50, width=80)
        # Bind keyboard and mouse events to functions
        self._text.bind("<ButtonRelease-1>", self._release)  # Don't need lambda if not changing args
        self._text.bind("<B1-Motion>", lambda event: self._track())  # Using lambda to remove event arg
        self._text.bind("<Key>", lambda event: self._type("Type", event)) # Using lambda to add prompt arg
        self._text.pack(padx=10, pady=(10, 0))
        self._tracking = False
        # Create label for displaying index info
        self._info = tk.Label(self, text="")
        self._info.pack(pady=10)

    @property
    def text(self):
        """Return text in textbox."""
        return self._text.get(1.0, tk.END)

    @text.setter
    def text(self, new_text):
        """Set text in textbox."""
        self._text.delete(1.0, tk.END)
        return self._text.insert(1.0, new_text)

    def _track(self):
        """Display start and end of selection in text box."""
        try:
            first = self._text.index(tk.SEL_FIRST)
            last = self._text.index(tk.SEL_LAST)
            self._info["text"] = f"Selection: {first} : {last}"
            self._tracking = True
        except tk.TclError:
            pass

    def _release(self, event):
        """Display cursor location after mouse click."""
        if not self._tracking:
            try:
                self._info["text"] = f"Index: {self._text.index(tk.INSERT)}"
            except tk.TclError:
                self._info["text"] = ""
        self._tracking = False

    def _type(self, prompt, event):
        """Display cursor location after typing."""
        try:
            self._info["text"] = f"{prompt}: {self._text.index(tk.INSERT)}"
        except tk.TclError:
            pass


window = TextTest()
# Load some text into the Text widget.
with open(__file__, "r") as file:
    window.text = file.read()
window.mainloop()
Run the code and select text in the text widget. The first and last indices of the selection are displayed in the label below the text widget. It doesn't matter if you drag right/down or left/up. The first index of the selection is always <= the last index.
Reply
#3
(Jul-02-2025, 01:40 PM)deanhystad Wrote: In Text, the index cannot be longer than END. If 10.END == 10.5, you cannot go to 10.6. This is reflected in the response to your test. 10.6 is past 10.END, so it becomes 10.END.

From TkDocs: https://tkdocs.com/tutorial/text.html
Quote:An index past the end of the text (e.g., end + 100c) is interpreted as end.
Thanks for clarifying how .END actually works. It seems a pain but I think I can work around it now that I know what is happening.

(Jul-02-2025, 01:40 PM)deanhystad Wrote: I've never used Text.compare() and am having difficulty thinking of a use case.

What I am trying to do is center messages inserted into the textbox when the size of the textbox is based on the screen of the users computer. So if width is 640,1080,1920,2560,or higher or some weird screen size like some laptops, the information is displayed in the center of the screen by changing the left margin in some cases and using the entire width in other cases. I don't want to center justify each line of text but put 40 to 100 spaces in front to center the information.
Reply
#4
That sounds like a bad idea to me, but if you need to know the length of the message, why not use len(str) on the message before appending text to the Text widget?

Why are you using a Text widget to display messages? It sounds like a job for Label which will automatically center the message.
Reply
#5
(Jul-09-2025, 04:07 AM)deanhystad Wrote: Center the textbox instead of trying to center the text inside the text box.
since the textbox is centered by the pack() method are you saying that I should change the width of the textbox to center the text I want to display ie: textbox.configure(width=60) for narrow information or textbox.configure(width=120) for full width text?
Reply
#6
You should post some code to provide context for your questions.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  recording textbox data into a variable paul18fr 4 2,507 Feb-19-2024, 09:30 PM
Last Post: Axel_Erfurt
  [Tkinter] Tkinter Textbox only showing one character Xylianth 1 3,562 Jan-29-2021, 02:59 AM
Last Post: Xylianth
  [Tkinter] Redirecting stdout to TextBox in realtime Gilush 2 13,545 Jun-06-2020, 11:05 AM
Last Post: deanhystad
  tkinter how to unselect text in textbox Battant 0 3,520 Feb-17-2020, 02:00 PM
Last Post: Battant
  [Tkinter] cannot type in textbox msteffes 2 4,585 Jul-28-2018, 04:20 AM
Last Post: msteffes
  GUI insert textbox value into a Class dimvord 0 3,230 Jul-04-2018, 06:49 PM
Last Post: dimvord

Forum Jump:
Image

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020