Python tkinter - 在文本小部件中自动缩进一行

Python tkinter - auto indent a line in Text widget

我正在尝试制作一个 tk.Textttk.Text 小部件..

其中,当您点击 <TAB> 时,它会缩进...

在那之后..

从下一行开始,直到标签被删除,它会缩进行

示例:

计算前导制表符的数量"\t"然后在下一行插入相同数量的制表符。

这是一个例子:

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

对于使用当前行使用的任何缩进(包括制表符和空格)的通用自动缩进器,您可以获取该行的空格,插入换行符,然后插入相同的空格。通过绑定到 <Return> 事件来做到这一点。

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