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

标签 python tkinter text

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

当你点击 <TAB> 时,它给出缩进...

之后..

从下一行开始,直到选项卡被删除为止,它将缩进

示例:

enter image description here

最佳答案

对于使用当前行使用的任何缩进(包括制表符和空格)的通用自动缩进器,您可以获取该行上的空格,插入换行符,然后插入相同的空格。通过绑定(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/

相关文章:

python - python 中的名称错误(类)

file - 无法使用 QDir::rename() 重命名 Qt 中的文件

java - 从文本文件中提取 XML 标签

python - ValueError : Error when checking target: expected dense_10 to have shape (1, )但得到了形状为(19316,)的数组

python - 如何确定 Python 生成器中的值是否为最后一个?

python - 如何在 Tkinter 中使用 Canvas 绘制点?

python - 将 python 海龟 Canvas 转换为位图时如何保持 Canvas 大小

java - 面板中的居中字符串

python - celery 击败不接受周期性任务

python - 在python中将字母数字字符串转换为数字字符串