Search code examples
pythontkintertkinter-text

Remove trailing space from tkinter Text widget


My goal here is to have the right edge of the text box fit to the end of the text. This happens automatically when using TkFixedFont, but when using TkDefaultFont (which is what I would like to use), there is trailing whitespace added to the end. This is what it looks like with no trailing space, with TkFixedFont:

Notice that the trailing space is minimal. I would like this same near-none amount of trailing space, but when using TkDefaultFont.


The following is a minimal example of my code:

from tkinter import *
root = Tk()

myText = 'sample text'

text = Text(root, bg='#c2d9ff', 
            font='TkDefaultFont',
            height=1, width=len(myText)
        )
text.insert(INSERT, myText)
text.place(x=0,y=0)
root.mainloop()

I have searched for around two hours now for everything related to spacing, trailing space, types of widgets (e.g., label vs text, etc.), widget options, etc., and have found nothing unfortunately.

It appears to somehow be proportional to the length of the text, which I cannot figure out. Using the code above, when myText = 'Some text goes here', the trailing spacing is:

But when I put a longer text string, the trailing space seems to proportionally increase:

Any suggestions on how to cut out the trailing space would be much appreciated!


Solution

  • You can get the area occupied by myText using Text.dlineinfo() and adjust the width of text based on the result and other settings related to space occupied horizontally, e.g. border width, padx, etc:

    myText = 'sample text'*4
    
    text = Text(root, bg='#c2d9ff',
                font='TkDefaultFont',
                height=1
            )
    text.insert(INSERT, myText)
    text.place(x=0, y=0)
    
    text.update_idletasks() # make sure the widget is laid out completely
    x, y, w, h, _ = text.dlineinfo(INSERT)
    text.place(width=x+w+(text['bd']+text['padx'])*2) # adjust the width