最佳答案
对于使用当前行使用的任何缩进(包括制表符和空格)的通用自动缩进器,您可以获取该行上的空格,插入换行符,然后插入相同的空格。通过绑定(bind)到 <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()
关于Python tkinter - 在文本小部件中自动缩进一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69496265/