Home > OS >  Python tkinter - auto indent a line in Text widget
Python tkinter - auto indent a line in Text widget

Time:10-09

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

CodePudding user response:

Count the number of leading tabs "\t" then insert the same number of tabs in the next line.

Here is an example:

import tkinter as tk

def autoIndent():

    index = f"{text.index('insert')}-1l linestart"
    string = text.get(index, f"{index} lineend")
    
    tab_count = len(string)-len(string.lstrip("\t"))
    text.insert("insert linestart", "\t"*tab_count)

root = tk.Tk()

text = tk.Text(root)
text.bind("<Return>", lambda ev:text.after(1, autoIndent))

text.pack()

root.mainloop()

CodePudding user response:

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()
  • Related