1
def generate_menu(self):
    self.some_menu = tk.Menu(self.menubar, tearoff=0)
    self.menubar.add_cascade(label="Some Label", menu=self.some_menu)

    some_directory = SCRIPT_ROOT + "/" + SOME_FOLDER

    for filename in os.listdir(some_directory):
        test_file = (test_directory + "/" + filename)
        print(test_file)
        self.some_menu.add_command(label=filename, command=lambda: self.files.add_files(test_file))

This code generates a menu item with a dropdown containing:

  • File 1
  • File 2
  • File 3

and so on.

Each file option should have an individual command calling the same function but with a different argument.

self.files.add_files(<argument should be based on iteration of for loop)

What is happening is that each file option is actually using the command for File 3 (or the last file on the dropdown).

There is a fault in logic somewhere - can you spot it?

Cov
  • 561
  • 5
  • 20
  • 2
    You are relying on closures; these are dereferenced when the function is *called*, not when it is defined. As such, the `test_file` name has moved on from when you printed it and now points to the last generated name. The solution is to not rely on a closure, see the duplicate. – Martijn Pieters Mar 29 '17 at 15:30
  • For example, `command=partial(self.files.add_files, test_file)` would work, as the `test_file` reference is captured in the `functools.partial()` object. – Martijn Pieters Mar 29 '17 at 15:31
  • Fantastic, it worked - thanks for the super fast reply and sorry for the duplicate! – Cov Mar 29 '17 at 15:36

0 Answers0