For example, in the loop I create three widgets for the Entry :

 from tkinter import * root = Tk() for i in range(3): e = Entry(root).pack() root.mainloop() 

How to bind a command (e.bind('<Return>',command)) to return the widget number?

    1 answer 1

    The easiest way to get the widget number is to explicitly add the required field to it:

     from tkinter import * from tkinter import messagebox def handler(event): messagebox.showinfo('', str(event.widget.number)) root = Tk() for i in range(3): e = Entry(root) e.pack() e.number = i e.bind('<Return>', handler) root.mainloop() 

    But this way of adding fields to a foreign class is not very good, because The selected name can intersect with the existing field, which can break the logic of the object.

    Another option is to make a "transitional" lambda function, which will "remember" the number of the widget to which it is associated:

     from tkinter import * from tkinter import messagebox def handler(event, number): messagebox.showinfo('', str(number)) root = Tk() for i in range(3): e = Entry(root) e.pack() e.bind('<Return>', lambda event, i=i: handler(event, i)) root.mainloop() 

    Another way: you can use the fact that tkinter objects are hashed, so you can use them as keys in a dictionary, the values ​​in which will be the numbers of the widgets:

     from tkinter import * from tkinter import messagebox to_index = dict() def handler(event): messagebox.showinfo('', str(to_index[event.widget])) root = Tk() for i in range(3): e = Entry(root) e.pack() e.bind('<Return>', handler) to_index[e] = i root.mainloop()