1

I have used two "for loops" to work through a list of c70 menu items to create a tkinter drop down menu bar. For each .add_command iteration, the for loop generates the label (section[i][1]) and a command=function which refers to an argument from the list (section[i][1]). However, by the time the menu item is selected and the function called, the function refers for its section[i][1] argument to the last list item in the original for loop. How can I set the function's argument as the loop generates each menu item, so that it does not change which each loop iteration?

The related code I have used is:

'''

from tkinter import Menu

for section in self.master.contents.subsection_list:
    # adds menu category sections
    menu_heading = section[0]
    menu_name = Menu(menu)
    menu.add_cascade(label=menu_heading, menu=menu_name)
    # adds components of menu category sections
    for i in range(1, len(section)):
        menu_name.add_command(label=section[i][1], command=lambda: print(section[i][1]))

'''

In case it is helpful ... each item within the list iterated through by the first "for loop" is structured:

[section[0], [section[1][0], section[1][1], section[1][2]], [section[2][0], section[2][1], section[2][2]], ...]

Thank you for your help.

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • You need to capture the lambda-value: `menu_name.add_command(label=section[i][1], command=lambda captured_i=i: print(section[captured_i][1]))`.. the `lambda captured_i=i: ... ` captures the value of i inside captured_i and uses that. Sometimes you see `lambda i=i: ... ` wich may be a bit too confusing if you do not know what is going on – Patrick Artner Apr 26 '22 at 15:25
  • good 1st question btw :) – Patrick Artner Apr 26 '22 at 15:30
  • .. and one more: [creating-lambda-inside-a-loop](https://stackoverflow.com/questions/7546285/creating-lambda-inside-a-loop) – Patrick Artner Apr 26 '22 at 15:34
  • Hi Patrick. Thank you very much for your answer. That is really helpful. Best wishes. – user18953909 Apr 26 '22 at 15:35

0 Answers0