Home > Software design >  Tkinter change paste command
Tkinter change paste command

Time:11-25

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!!

CodePudding user response:

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)
  • Related