【问题标题】:Python tkinter - auto indent a line in Text widgetPython tkinter - 在文本小部件中自动缩进一行
【发布时间】:2021-11-28 10:29:19
【问题描述】:

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

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

在那之后..

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

示例:

【问题讨论】:

    标签: python tkinter text


    【解决方案1】:

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

    【讨论】:

    • 有错字。将line 更改为prev_line,反之亦然。
    • @acw1668:感谢您的关注。我已经修好了。
    【解决方案2】:

    计算前导标签的数量"\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()
    

    【讨论】:

    • 你的回答也很好,但@Brian Oakley 的回答有点简单......
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2013-05-24
    • 2012-02-09
    • 2016-01-15
    • 1970-01-01
    • 2012-02-14
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多