Tkinter change paste command

Question:

I’m trying to change paste command on my program. When we copy table value from excel, whether it’s vertical or horizontal line, it will converted to vertical entries list. But the problem is when I only want to paste single value to the random entries line, it will always print the value from 1st line entry and not from the entry line that I selected. Is it also possible create function to select all entries with mouse?

This is my code:

from tkinter import *

root=Tk()
d=[]
for i in range(4):
    e=Entry(root,)
    e.grid(row=i)
    d.append(e)

def paste(event):
    for entry in d:
        entry.delete(0,'end')
    data=root.clipboard_get().split()
    for entry,i in zip(d,data):
        if 'n':
            entry.insert(0, i.split('n'))
            print(data)
        elif 't':
            entry.insert(0, i.split('t'))
            print(data)
    return 'break'

root.bind_all("<<Paste>>", paste)

root.mainloop()

Can you help me solve this problem?

Thank you!!

Asked By: Eten13

||

Answers:

It is because the for loop always starts from the first entry box. You need to find the index of the selected entry in the entry list d and paste the clipboard data starts from it:

def paste(event):
    try:
        # get selected entry
        w = root.focus_get()
        # get the index of the selected entry in the entry list
        idx = d.index(w)
        # get the data from clipboard and split them into list
        data = root.clipboard_get()#.rstrip() # strip the trailing 'n'
        #print(repr(data)) # for debug purpose
        if 't' in data:
            data = data.split('t')
        elif 'n' in data:
            data = data.split('n')
        # paste the data starts from the selected entry
        for entry, txt in zip(d[idx:], data):
            entry.delete(0, 'end')
            entry.insert('end', txt)
        return 'break'
    except Exception as ex:
        # something wrong, like no entry is selected
        print(ex)
Answered By: acw1668
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.