Home > Mobile >  Indent all words selected with the tab command with tkinter
Indent all words selected with the tab command with tkinter

Time:11-02

When I use the tkinter text in Python if I select a block of words with the mouse and press the tab command, only the first word will be indented. Is there a way to have all the selected words indented?

CodePudding user response:

One way to achieve this is to get the selection index and insert \t in each line.

here is an example

import tkinter as tk


def tab(event):
    
    try:
        start_line = int(text.index("sel.first")[0])
        last_line = int(text.index("sel.last")[0])
        
        for x in range(start_line, last_line 1):
            text.insert(f"{x}.0", "\t")

        return 'break'

    except tk.TclError:
        pass

root = tk.Tk()

text = tk.Text(root)
text.pack(expand=True, fill="both")
text.bind("<Tab>", tab)

root.mainloop()

text.index("sel.first") returns the index of the first selection and the text.index("sel.last") returns the index of the last selection.

  • Related