Search code examples
pythonsqlitetkinterbind

tkinter for loop entry bind connected to sqlite3


I am having difficulty in returning the right sqlite3 row with a bind of an entry created in for loop

i know, i don't know how to explain it with words so here's the piece of code

    if x == '':
        counter_kit_label = 10
        for kit in find_everything_from_db('*', 'kit'):
            kit_label = tk.Label(self.kit_listbox, text=f"{kit[0]}, {kit[1].capitalize()}, {kit[2].capitalize()},",
                                 bg='white')
            kit_label.place(x=5, y=counter_kit_label)
            kit_label.bind('<Enter>', lambda event: evidenzia(event))
            kit_label.bind('<Leave>', lambda event: non_evidenzia(event))
            kit_label.bind('<Button-1>', lambda: None)  # todo: creare event bind
            kit_entry_var = tk.StringVar()
            kit_entry = tk.Entry(self.kit_listbox, textvariable=kit_entry_var)
            kit_entry_var.set(f"{kit[4].capitalize()}")
            kit_entry.place(x=108, y=counter_kit_label)
            kit_entry.bind('<Return>', lambda event: self.modifica_luogo_kit(kit_entry.get(), kit, event))
            counter_kit_label += 30
    else:
        pass
def modifica_luogo_kit(self,luogo, kit, event=None):
    print(event.widget.get())
    print(kit)

when i run the script and press 'return-key' on the first tk.Entry, the print result of "print(event.widget.get())" correspond to the first entry preset from the first row of sqlite3 tab but "print(kit)" correspond to the latest row of sqlite3 tab


Solution

  • Try this:

    import tkinter as tk
    from functools import partial
    
    def modifica_luogo_kit(luogo, kit, event=None):
        print("Data in widget =", luogo.get())
        print("Entry number:", kit)
    
    root = tk.Tk()
    
    for kit in range(10):
        kit_entry = tk.Entry(root)
        kit_entry.pack()
        command = partial(modifica_luogo_kit, kit_entry, kit)
        kit_entry.bind("<Return>", command)
    

    I removed all of the unnecessary details to make it easier to solve the problem. I used functools.partial to create a command that is executed when "<Return>" is pressed. For more info on functools.partial look at this.