I've decided to start on a Tkinter project to get an even better understanding of Tkinter and to expand my knowledge. I've decided to make a notepad and I've managed to do it except a small problem I've bumped into. I want to make a custom shortcut in Tkinter that will help me copy long lines of text without having to scroll a lot. I know there are shortcuts like using Shift
to copy from where the cursor is, but what I want to do is make my own custom shortcut. Let's say, for example, pressing Ctrl Q
will copy the whole line that the cursor is on or something similar. If possible, it would also be a nice feature to be able to select
the current line without copying it using another custom shortcut. For example, see image:
I've done a lot of research about this problem but I haven't managed to find anything useful as information. I don't want to use a shortcut that already exists in windows, since I want to make my own custom shortcuts. The problem is not about how I use the bind feature, the problem is how I would go about actually making a function that would select the line and copy it.
Thank you! :)
CodePudding user response:
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()