Search code examples
pythontkintertkinter-entry

Get values from each entry box through individual button for each box


I created Entry and buttons through a loop, like this

for i in range(len(headers)):
        pos_y = 0;

        e = tk.Entry(top, width = 30);
        e.grid(row = pos_x, column = pos_y);
        entry[i] = e;
        e.insert(0, headers[pos_x].get('name'));
        pos_y += 1;

        b = tk.Button(top, text = 'Copy');
        b.grid(row = pos_x, column = pos_y);
        button[i] = b;
        pos_y += 1;

I've two dicts for Entry and Button each, output is like this. Output

What I want to do is for each of the buttons, I want to copy value from the textbox to clipboard. I know how to copy to clipboard, just getting the corresponding value is the problem. Edit: Header is a list of dictionaries; pos_x is used to switch from one row to other; pos_y is used to switch to next coulmn. Here I'm iteration over a dictionary to get names from dict to 1st textbox and values to another. like this :{"name": "key", "value": "2500"} button and entry are dicts, declared above as entry{} and button{}.


Solution

  • I think you are making things more complicated than they need to be. You do not need to place your buttons in a dict/list as you are not changing them after they are created. Instead think about using a simple list to story your entry values and then use their index to call the get method on them when you need them.

    Here is my example. Let me know if you have any questions.

    import tkinter as tk
    
    
    class Example(tk.Tk):
        def __init__(self):
            super().__init__()
            self.entry_list = []
    
            r = 0
            c = 0
            for i in range(6):
                self.entry_list.append(tk.Entry(self, width=30))
                self.entry_list[-1].grid(row=r, column=c)
                tk.Button(self, text='Copy', command=lambda ndex=i: self.copy_to_clipboard(ndex)).grid(row=r, column=c+1)
                if r == 2:
                    c += 2
                    r = 0
                else:
                    r += 1
    
        def copy_to_clipboard(self, ndex):
            print(self.entry_list[ndex].get())
            self.clipboard_clear()
            self.clipboard_append(self.entry_list[ndex].get())
    
    Example().mainloop()
    

    Results:

    enter image description here