Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

tkinter: get index of a clicked widget inside a list of widget objects

The following code creates a list of tk entry widgets and then displays them in a tk root window. Each entry includes a binding to a left mouse click that calls an event handler. The event handler identifies which entry widget was clicked using event.widget.

def event_handler(event):
    clicked_entry = event.widget
    print(clicked_entry)
    
# Create list of tk entry widgets
    entry_list = []
    for index in range(0,10):
        entry = tk.Entry(root)
        entry.bind('<Button-1>',event_handler)
        entry_list.append(entry)
    
# Display entry widgets on screen
    for index in range(0,10):
        entry_list[index].pack(side=tk.TOP)

The output of the event handler, for index items 0, 1 and 2, is as follows:

.!entry    # index 0
.!entry2   # index 1
.!entry3   # index 2

So I have written a revised event handler that manipulates the event.widget information to produce a correct index value:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def event_handler(event):
    clicked_entry = event.widget
    entrystr = str(clicked_entry)
    stripped_entrystr = entrystr.replace(".!entry","")
    if stripped_entrystr == "":
        clicked_index = 0
    else:
        clicked_index = int(stripped_entrystr)-1
    print(clicked_index)

This works perfectly, and produces an integer representing the correct index of the clicked entry widget in the list. However, it seems like a laborious way to get at this information. I wonder if there is a simple method to accomplish the same thing – with emphasis on ‘simple’ – I have seen solutions to similar questions on Stack Overflow that were very complex (and beyond my understanding). If there is no simpler solution, then I’d appreciate knowing if there is anything wrong with my approach that I should be aware of. Thanks in advance.

>Solution :

def event_handler(event):
    clicked_entry = event.widget
    print(entry_list.index(clicked_entry))

Inside the event_handler function, we get the clicked widget clicked_entry using event.widget and then get its index inside the widgets list using entry_list.index(clicked_entry). Finally, we print the index to the console.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading