python - tkinter 文本小部件 : how to indent automatically after a soft line wrap

标签 python tkinter text

在行开头输入连字符时,我希望 Text 小部件将以下文本视为后续行缩进的部分,如下所示:

  • 通过输入这个连字符(我的意思是连字符,而不是自动生成的那个项目符号)要缩进的部分开始。到达右边界时,
    执行软换行(我正在使用 wrap=tk.WORD),新行应该看起来像
    这里。

  • 相反,新行从左边框开始,没有缩进。
    在 Text 小部件的属性中,我发现 spacing1、spacing2、spacing3 都指垂直行距。没有提示水平间距。我是否缺少适当的属性,还是必须从头开始编写所需的行为?
    如果是这样,我将不得不绑定(bind)到换行事件,但我认为没有。
    有谁知道如何解决这个问题?

    最佳答案

    您可以添加属性 lmargin1lmargin2到标签,然后将该标签应用于文本范围以控制左边距。
    这是一个示例(如果您使用不是命名字体的自定义字体,则必须调整查询字体的部分):

    import tkinter as tk
    from tkinter import font
    
    root = tk.Tk()
    text = tk.Text(root, wrap="word", width=40, height=10)
    text.pack(fill="both", expand=True)
    
    text_font = font.nametofont(text.cget("font"))
    bullet_width = text_font.measure("- ")
    em = text_font.measure("m")
    text.tag_configure("bulleted", lmargin1=em, lmargin2=em+bullet_width)
    
    message = (
        "by entering this hyphen (I really mean hyphen, not that bullet "
        "that is automatically generated) the section to be indented starts. "
        "When reaching the right border, a soft wrap is performed (I'm using "
        "wrap=tk.WORD) and the new line should look like it does here."
    )
    
    text.insert("end", "- " + message, "bulleted")
    
    root.mainloop()
    
    screenshot

    关于python - tkinter 文本小部件 : how to indent automatically after a soft line wrap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63488244/

    相关文章:

    java - 为什么我的方法只读取一行文本?

    python - 将 2 个 csv 文件与一个唯一列但不同的标题合并

    python - Django 管理员,自定义错误消息?

    python-2.7 - Tkinter 列表框、箭头键与鼠标单击的行为差异

    Python Tkinter 命令单击

    r - 将文档术语矩阵转换为包含大量数据的矩阵会导致溢出

    php - 使用PHP替换文本文件中的字符串

    python - 从 Pandas 中的相关矩阵返回最高和最低相关

    Python Selenium 单击带有类的按钮

    python - tkinter 在 Canvas 上可变值