select a line of text using a shortcut in the text widget tkinter

It is pretty simple, you just need to make use of Text widget indices, they provide great functionality. The most useful in this case are 'insert' and 'linestart' and 'lineend' as they easily allow to select the entire line where the cursor is. The rest is pretty simple:

import tkinter as tk


def copy_line(event=None):
    data = text.get('insert linestart', 'insert lineend')
    root.clipboard_clear()
    root.clipboard_append(data)


def select_line(event=None):
    # `sel` is a special tag name that represents the current selection if any
    text.tag_add('sel', 'insert linestart', 'insert lineend')


root = tk.Tk()

text = tk.Text(root)
text.pack()

text.bind('<Control-q>', copy_line)
text.bind('<Control-e>', select_line)

root.mainloop()

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top