Search code examples
functionlambdaparameter-passing

Python pass while value to function using lambda


I am trying to pass a while value to a function so that I don't have to write lots of code.

IamInfo is an array of information example: 0: JobNo : JobCode : List of items (again variable length)

My code:


q=0
while q < len(IamInfo):
  Left.insert(INSERT,IamInfo[q][2]+"\n")
  Left.bind("<Button-1>", lambda event, arg=q: displayMore(arg))
  q += 1

Ineed to pass the q value as I use it as a key to display the last column of information in another tkinter frame. the length of IamInfo can change from 2 items to 20 so I need to be able to use this for many different number of items. enter image description here

called function

def displayMore(key):
  print (key)                  <--- so I can see what is passed only
  DisLoop = len(IamInfo[key])
  disx = 4                     <--- defines array element to display
  while disx < DisLoop:
    disText = str(IamInfo[key][disx])+"\n"
    Right.insert(INSERT, disText)
    disx += 1

With the above code it only passes the last q value for all links. I have tried several different ways, but either fails or just passes last q value.

Any help would be great.


Solution

  • So I resolved this by changing how I called the function.

    Instead of:

    Left.insert(INSERT,IamInfo[q][2]+"\n")
      Left.bind("<Button-1>", lambda event, arg=q: displayMore(arg))
    

    I used:

    but=Button(Left,width=25,text=IamInfo[q][1],command= partial(displayMore,key=q)).pack()
    

    This called the function with while passing the loop value at the time of creation.