Search code examples
pythontkintertext

Python tkinter - auto indent a line in Text widget


I am trying to make a tk.Text or ttk.Text widget..

In which when you hit <TAB>, it gives indent...

after that..

from the next line onwards, untill the tab is deleted it will indent lines

example:

enter image description here


Solution

  • For a general-purpose auto-indenter that uses any indentation used by the current line including tabs and spaces, you can get the whitespace on the line, insert a newline, and then insert the same whitespace. Do this by binding to the <Return> event.

    import tkinter as tk
    import re
    
    def auto_indent(event):
        text = event.widget
    
        # get leading whitespace from current line
        line = text.get("insert linestart", "insert")
        match = re.match(r'^(\s+)', line)
        whitespace = match.group(0) if match else ""
    
        # insert the newline and the whitespace
        text.insert("insert", f"\n{whitespace}")
    
        # return "break" to inhibit default insertion of newline
        return "break"
    
    root = tk.Tk()
    text = tk.Text(root)
    text.pack(side="top", fill="both", expand=True)
    
    text.bind("<Return>", auto_indent)
    
    root.mainloop()