Search code examples
pythontkintertextword-wrap

Can I force the tkinter.Text widget to wrap lines on the "space" character as well as words?


Below is an example tkinter app with a Text field which wraps to the next line on long words, as expected. The issue, however, is that spaces don't wrap to the next line in the same way. I am able to enter as many spaces as I like prior to the start of a new word and a line wrap won't occur. Once I begin typing any other printable characters (as well as tabs and newlines), the text wraps as expected.

How can I configure my Text widget to also wrap on whitespace at the end of the line? Is there a better method than, say, parsing out the length of the line in question (with Text.count(), perhaps) and forcing a newline after width characters?

import tkinter as tk


root = tk.Tk()
text = tk.Text(root, wrap='word', width=40, height=10)
text.pack(expand=True, fill='both')


if __name__ == '__main__':
    root.mainloop()

Solution

  • Simply wrap spaces in a tag with wrap option set to "char".

    import tkinter as tk
    
    
    root = tk.Tk()
    
    class Text(tk.Text):
        def __init__(self, master, **kwargs):
            tk.Text.__init__(self, master, **kwargs)
            self.bind('<KeyPress-space>', self.char_space)
            self.tag_configure('space', wrap='char')
        
        def char_space(self, event=None) -> str:
            self.insert('insert', ' ', 'space')
            return 'break'
    
           
    text = Text(root, wrap='word', width=40, height=10)
    text.pack(expand=True, fill='both')
    
        
    if __name__ == '__main__':
        root.mainloop()