pythonloopseventseventhandler

How to loop over an array and create a unique event handler for each item


In my application, I have a list of apps,

apps = [
    App("app1", "username1", "password1", "----"),
    App("app2", "username2", "password2", "----"),
    App("app3", "username3", "password3", "----"),
]

(App() is simply a class that contains data for each app)

Later in the code, I loop over this array to create a label widget for each app.

appLabels = []

for a in apps:
    lbl = ptg.Label(a.name)
    def left_mouse():
        showEditForm(a)
    lbl.on_left_click = lambda _: left_mouse()
    appLabels.append(lbl)

However, when i click on any of the labels, it always calls showEditForm() with app3. How can I create a unique event handler for each app that will call showEditForm() with the right app?


Solution

  • When you iterate over a list, the function left_mouse will be re-defined each time, and the lambda will refer to the latest one, in your case, the third one, and the a variable in the function will also be the last one. To solve the issue, consider adding a parameter with a default unique value (maybe a in your case) to the lambda and left_mouse functions. The code will like this:

    appLabels = []
    
    def left_mouse(app):
        showEditForm(app)
    
    for a in apps:
        lbl = ptg.Label(a.name)
        lbl.on_left_click = lambda _, app=a: left_mouse(app)
        appLabels.append(lbl)